我有模特帖子:
protected $with = ['user']
public function user() {
return $this->belongsTo(User::class);
}
在控制器上我只设置标题和图像:
$posts = Post::get(['title', 'image']);
关系用户返回null。
@foreach($posts as $post)
User: {{ $post->user->name }} //null
@endforeach
为什么?如果我从get
方法删除数组,那么关系正在工作,如果我设置数组,那么关系用户返回null。请帮忙。
使用Post::get(['title', 'image']);
,您指定只需要这些列。
如果你想使用这种方法,
$posts = Post::with('user')->get(['title', 'image']);
或者您可以包含不使用protected $with
属性的用户,而是将protected $appends
添加到您的模型中作为默认字段
// In Post Class:
protected $appends = "user";
// Then this should work
$posts = Post::get(['title', 'image', 'user']);