Laravel 中的关系雄辩?

时间:2021-07-30 15:49:46

标签: php laravel laravel-5

user中:

public function posts()
{
    return $this->hasMany(Post::class);
}

post中:

public function users()
{
    return $this->belongsTo(Users::class);
}

我在控制器中处理:

$user = Users::find('1')->posts;

然后我得到一个数组,返回的结果正是我需要的。

但是我这样查询的时候因为需要获取很多数据,结果是一个空数组。我做错了什么?

UserController.php中:

$listUser = Users::with('posts')
    ->select('name', 'title')
    ->where('type', 1)
    ->get(); // It returns posts as an empty array

请给我任何意见。

3 个答案:

答案 0 :(得分:1)

您的关系是使用主键开发的,在您的查询中,您缺少 id 来获取值。

$listUser = Users::with('posts')
    ->select('users.id', 'users.name', 'posts.title')
    ->where('posts.type', 1)
    ->get(); 

答案 1 :(得分:1)

您必须在 foreign key 中选择 posts

$listUser = Users::select(['id', 'name'])
    ->with(['posts' => function($query) {
        $query->select(['user_id','title']);
    }])
    ->where('type', 1)
    ->get();

$result = User::select(['id', 'name'])
    ->with(['posts:user_id, title'])
    ->get();

答案 2 :(得分:1)

如果您只想选择相关模型的某些字段,您可以在 with 子句中指定它,如下所示。 select 子句适用于 User 查询构建器。

$listUser = Users::with('posts:user_id, title')
    ->select('name')
    ->where('type', 1)
    ->get();