假如我们现在有两张表:user 和 posts,每个 User 可以拥有多个 Posts,而每一篇 Post 只能属于一个 User。下面分别是 User Model 和 Post Model 中定义的关系:
// User.php
public function post(){
return $this->hasMany('post');
}
// Post.php
public function user(){
return $this->belongsTo('user');
}
通过 with() 方法,我们可以这样获取所有的 Posts 并同时查出对应的 User 信息,可以使用这样的方法:
public function getAllPosts() {
return Post::with('user')->get();
}
这实际上会执行下面两句 SQL 语句:
select * from `posts`
select * from `users` where `users`.`id` in (<1>,<2>)
但是我们可能并不需要 User 表中所有的字段,例如我们只需要 id 和 username 两个字段:
select * from `posts`
select id,username from `users` where `users`.`id` in (<1>,<2>)
我们可以通过下面两种方法来实现。
方法一:在 with() 中指定
Post::with(array('user'=>function($query){
$query->select('id','username');
}))->get();
方法二:修改 Model 文件
修改 Post.php 文件中 user() 方法:
public function user()
{
return $this->belongsTo('User')->select(array('id', 'username'));
}
洋果子店rose最新版本
洋果子店最新版是一款十分容易让人垂涎的开店经营类手游。游戏玩
明日大亨最新版
明日大亨手游,一个非常经典有趣的模拟经营类型的商战手游,在游
早安我的少年日服最新版2024
早安我的少年日服是一款治愈恋爱手游,清新明亮的游戏画面,让你
我的世界基岩版1.16正式版
我的世界基岩版是一款模拟经营手游,游戏采用的是经典像素玩法,
早安我的少年最新版2024
早安我的少年是一款养成恋爱手游,在这款游戏中,玩家们将可以体