简体   繁体   English

Laravel 从关系中提取字段

[英]Laravel pluck fields from relations

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:我需要从 LaravelCollective 中填充一个选择,所以我需要做这样的事情:

{!! 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).问题是我不能从关系 (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;
    });
?>

您可以使用Laravel的pluck方法为:

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

You can achieve it by using join() & pluck() like this:您可以通过使用join()pluck()来实现它,如下所示:

$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!希望这有帮助!

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

try with below solution it's working for me as i am using laravel 8尝试使用以下解决方案它对我有用,因为我正在使用 laravel 8

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM