Laravel pluck fields from relations

為{幸葍}努か 提交于 2019-12-17 10:59:07

问题


I have a Seller object which has a related User. I need to fill a select from LaravelCollective so I need to make something like this:

{!! Form::selectGroup('seller_id', 'Seller', Seller::with('user')->pluck('user.first_name', 'id')->toArray(), null) !!}

The problem is that I cannot take fields from relationships (user.first_name).

How can I do it?

UPDATE

I want to avoid doing this...

<?php 
    $sellers = [];

    Seller::with('user')->get()->each(function ($seller) use (&$sellers) {
        $sellers[$seller->id] = $seller->user->first_name;
    });
?>

回答1:


You can use Laravel's pluck method as:

$sellers = Seller::with('user')->get()->pluck('user.first_name', 'id')



回答2:


You can achieve it by using join() & pluck() like this:

$s = Seller::join('users', 'sellers.user_id', '=', 'users.id')
          ->pluck('sellers.id', 'users.id')
          ->all();

This would give an array like this:

[
    'seller_id_1' => 'user_id_1',
    'seller_id_2' => 'user_id_2',
    'seller_id_3' => 'user_id_3',
    'seller_id_4' => 'user_id_4',
    'seller_id_n' => 'user_id_n',
];

Hope this helps!




回答3:


Another way to do it is to define what columns you need inside the relationship. It's good if you always need just these columns on the given relationship. Example:

Class Seller extends Model {
    ...

    public function user()
    {
        return $this->hasOne(user::class, 'id')
            ->select('id', 'first_name');
    }
}


来源:https://stackoverflow.com/questions/40635146/laravel-pluck-fields-from-relations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!