Laravel从模型中获取具有特定数据和关系的记录

问题描述 投票:0回答:1

我有模特帖子:

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。请帮忙。

php laravel
1个回答
0
投票

使用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']);
© www.soinside.com 2019 - 2024. All rights reserved.