简体   繁体   English

从 Laravel 中预先加载的第一个表中选择特定列

[英]select specific columns from first table with eager loading in Laravel

I have checked many solutions to get specific columns from first model with eager loading but nothing works in my case.我已经检查了许多解决方案以从第一个模型中获取特定列,但在我的情况下没有任何效果。

for example: I want specific columns from model User and want to get relationship data with eager loading without any join.例如:我想要来自模型User特定列,并且想要在没有任何连接的情况下通过预先加载来获取关系数据。

$users= User::select('name') // get one column from user table
->with(array('role_user' => function($query){
    $query->select('role_name'); // and select one column from pivot table
}))
->paginate(3);

when I don't use User::select('name) , it returns relationship data with eager load when I use select, it returns empty array.当我不使用User::select('name) ,当我使用 select 时,它返回带有急切加载的关系数据,它返回空数组。

How I can get specific columns from both tables using eager loading如何使用预先加载从两个表中获取特定列

I don't exactly know, how you defined your relationship but Laravel has some weird behavior : You should always also select the primary and foreign keys:我不完全知道,你是如何定义你的关系的,但 Laravel 有一些奇怪的行为:你也应该总是选择主键和外键:

$users= User::select(['id', 'name']) // get one column from user table
->with(array('role_user' => function($query){
    $query->select(['id', 'role_name']); // and select one column from pivot table
}))
->paginate(3);

You can simplify it to this:您可以将其简化为:

$users= User::select(['id', 'name']) // get one column from user table
->with(['role_user:id,user_id,role_name']) // and select one column from pivot table
->paginate(3);

We Never Know the schemas and the relationships of your project.. But I assume You This Should Work我们永远不知道你的项目的模式和关系......但我认为你应该这样做

$users = User::select('id','name') 
               ->with(['role_user:id,user_id,role_name'])
               ->paginate(3);

In your User Model Relationships must be在您的用户模型关系中必须是

public function role_user(){
return $this->belongsToMany(Role::class, 'role_user'); // pivot table name
}

In your Role Model在你的榜样

 public function users(){
return $this->belongsToMany(User::class, 'role_user'); // pivot table name
}

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

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