php Laravel 从关系中提取字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40635146/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel pluck fields from relations
提问by Alan
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;
});
?>
回答by Amit Gupta
回答by Saumya Rastogi
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!
希望这可以帮助!
回答by Vali Munteanu
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');
}
}