【问题标题】:Get specific fields from both parent and child models从父模型和子模型中获取特定字段
【发布时间】:2016-06-26 01:47:18
【问题描述】:

我正在尝试检索模型实例及其相关实例,以便仅从 both 检索某些字段。 Thisthis 问题回答了如何为相关模型做到这一点,它对我很有效:

$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] => 
)

那么,如何只从主模型和相关模型中检索某些字段?

更新

在我看到 cresjie 的回答后,这对我有用:

$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');
}

【问题讨论】:

    标签: php laravel eloquent laravel-5.1 eager-loading


    【解决方案1】:

    Thread 数据未检索到,因为您还需要选择 Post 中的外键

    【讨论】:

    • 哇,就是这样,谢谢!但是,外键已经在Post 模型的thread 方法中定义。有什么方法可以让 Laravel 自动将其添加到 select 调用中,以避免两次指定外键?
    猜你喜欢
    • 2020-07-07
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 2016-08-11
    • 1970-01-01
    • 2020-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多