以下代码运行良好:
Post::with(['user'])
->get();
但是当我尝试使用 select 过滤它时,它在用户关系中返回 null。
Post::with(['user' => function($query){
$query->select('name');
}])
->select('id', 'slug', 'title', 'body', 'created_at')
->get();
用户模型中的关系:
public function posts()
{
return $this->hasMany('App\Post');
}
Post模型中的关系:
public function user()
{
return $this->belongsTo('App\User', 'user_id');
}
您必须选择外键(
posts.user_id
)和所有者键(users.id
):
Post::with(['user' => function($query){
$query->select('id', 'name');
}])
->select('id', 'slug', 'title', 'body', 'created_at', 'user_id')
->get();
您也可以使用这个较短的版本:
Post::with('user:id,name')
->select('id', 'slug', 'title', 'body', 'created_at', 'user_id')
->get();
你能做吗
DB::table('users')->where('votes', '>', 100)->sharedLock()->get();
您需要将 foreign_key 添加到 select 语句中。