我正在尝试检索模型实例及其相关实例,以便仅从两者中检索某些字段。这个问题回答了如何为相关模型执行此操作,它对我来说效果很好:
$hash = 'Post::whereId(1075)
->with(['thread' => function($query) {
$query->select('id', 'title');
}])
->first()
->toArray();
print_r($hash);
Array
(
[id] => 1075
[title] => Blablablablam,
[text] => Blablablablablablabl,
[created_at] => 2015-10-17 13:00:00
[updated_at] => 2015-10-17 13:00:00
[thread] => Array
(
[id] => 180
[title] => Blablablablam
)
)
但是,如果我也尝试限制Post
模型的字段,则根本不会检索Thread
数据:
$hash = 'Post::whereId(1075)
->with(['thread' => function($query) {
$query->select('id', 'title');
}])
->addSelect('title')
->first()
->toArray();
print_r($hash);
Array
(
[title] => Blablablablam,
[thread] =>
)
那么,如何仅从主模型和相关模型中检索某些字段?
更新
以下是我看到克雷斯杰的答案后对我有用的东西:
$hash = 'Post::whereId(1075)
->with(['thread' => function($query) {
$query->select('id', 'title');
}])
->addSelect('title', 'thread_id')
->first()
->toArray();
print_r($hash);
Array
(
[title] => Blablablablam,
[thread_id] => 180,
[thread] => Array
(
[id] => 180
[title] => Blablablablam
)
)
唯一仍然让我感到困惑的是外键 ( thread_id
) 需要显式指定,即使它已经在 Post
类中指定:
public function thread()
{
return $this->belongsTo(Thread::class, 'thread_id');
}
未
检索Thread
数据,因为您还需要选择Post
中的外键