【问题标题】:Laravel Eager Loading: select only few columns from polymorphic relationshipLaravel Eager Loading:从多态关系中仅选择几列
【发布时间】:2017-05-23 19:41:55
【问题描述】:

我怎样才能从多态关系中只加载特定的列?

我有一个 people 表,它可以变形为用户和机器人,我只需要从其中加载 first_namelast_name 以进行特定查询。

我试过this solution 没有运气,因为它似乎不适用于多态关系......它只是忽略了->select() 并按应有的方式加载所有内容。

有什么想法吗?

编辑: 这是相关查询

$school->load(array(
                'associationsTeachers' => function($q){
                    $q->with(array(
                            'person' => function($q2){
                                $q2->with(array(
                                    'account' => function($q3){
                                        $q3->select(array('id', 'first_name', 'last_name', 'person_id', 'account_id', 'account_type' ));
                                    }
                                ));
                            },
                    ));
                }
            ));

这里是关系

table: 'people';
public function account(){
    return $this->morphTo();
}

用户

table: 'users'
public function person(){
    return $this->morphOne('Person', 'account');
}

机器人

table: 'bots'
public function person(){
    return $this->morphOne('Person', 'account');
}

【问题讨论】:

标签: laravel laravel-4 eloquent


【解决方案1】:

使用它可以帮助你

Person::with(["account" => function($query) {
   $query->select("accountable_id", "first_name",  "last_name");
 }])

【讨论】:

    【解决方案2】:
    ParentModel::with(['relationship' => function ($q) {
        $q->select('relationship_table.only_this', 'relationship_table.this_too', 'relationship_table.foreign_key');
    }])->get();
    

    这应该可行。小心包含外键(和变形类型,因为您使用的是多态关系),因为查询需要它来查找相关模型。

    编辑:

    我也在多态关系(我在我的一个项目中设置)上尝试过这个,它按预期工作(只返回选定的列):

    public function relationship()
    {
        return $this->morphedByMany(\FullNS\RelationModel::class, 'pagable')
            ->select(['relation_table.id', 'relation_table.key]);
    }
    

    编辑 2:

    这样的事情应该可以工作。但它希望所有选定的列都在accounts 表中(我猜这是不正确的假设)。从你的问题我不知道哪些表有哪些列。

    $school->load(['associationsTeachers' => function ($q) {
        $q->with(['person' => function ($q) {
            $q->with(['account' => function ($q) {
                $q->select('accounts.id', 'accounts.first_name', 'accounts.last_name', 'accounts.person_id', 'accounts.account_id', 'accounts.account_type');
            }]);
        })];
    }]);
    

    【讨论】:

    • 这正是我尝试过的,但它不起作用。我还按照您的建议放置了变形键,但没有运气。我认为问题源于这样一个事实,即这不被视为加入......
    • @clod986 它没有执行连接。它正在执行另一个查询以获取相关结果。但如果您的关系和模型设置正确,它应该可以工作。请发布您的模型与关系和您尝试执行的确切查询。
    • @clod986 我已经更新了我的答案。我还测试了这两个选项,它们都工作正常。问题肯定出在其他地方。
    • 我已经更新了我的问题。请记住我在 laravel 4.2
    • @clod986 您确定这些关系有效(例如,您逐个测试,它们会返回您期望它们返回的内容)?那么另一个问题 - 所有这些列都保存在哪里('id', 'first_name', 'last_name', 'person_id', 'account_id', 'account_type')?
    猜你喜欢
    • 2017-08-27
    • 2021-10-17
    • 1970-01-01
    • 2020-05-23
    • 1970-01-01
    • 1970-01-01
    • 2013-06-04
    • 2018-01-10
    • 1970-01-01
    相关资源
    最近更新 更多