php Laravel Eager Loading - 仅加载特定列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16994253/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:02:20  来源:igfitidea点击:

Laravel Eager Loading - Load only specific columns

phplaravellaravel-4

提问by ipengineer

I am trying to eager load a model in laravel but only return certain columns. I do not want the whole eager loaded table being presented.

我正在尝试在 Laravel 中急切加载模型,但只返回某些列。我不希望呈现整个急切加载的表格。

public function car()
{
    return $this->hasOne('Car', 'id')->get(['emailid','name']);
}

I am getting the following error:

我收到以下错误:

log.ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Call to undefined method Illuminate\Database\Eloquent\Collection::getAndResetWheres()'

log.ERROR: 异常 'Symfony\Component\Debug\Exception\FatalErrorException' 带有消息 'Call to undefined method Illuminate\Database\Eloquent\Collection::getAndResetWheres()'

回答by rmobis

Make use of the select()method:

使用select()方法:

public function car() {
    return $this->hasOne('Car', 'id')->select(['owner_id', 'emailid', 'name']);
}

Note:Remember to add the columns assigned to the foreign key matching both tables. For instance, in my example, I assumed a Ownerhas a Car, meaning that the columns assigned to the foreign key would be something like owners.id = cars.owner_id, so I had to add owner_idto the list of selected columns;

注意:请记住添加分配给与两个表匹配的外键的列。例如,在我的示例中,我假设 aOwner有 a Car,这意味着分配给外键的列将类似于owners.id = cars.owner_id,因此我必须添加owner_id到所选列的列表中;

回答by Ali

Also you don't need to specify getting specific columns in the model and the relationship method itself... You can do that whenever you need it... Like this:

此外,您不需要指定在模型中获取特定列和关系方法本身......你可以在需要时这样做......像这样:

$owners = Owner::
          with([
           'car' => function($q)
           {
            $q->select('id', 'owner_id', 'emailid', 'name');
           },
           'bike' => function($q)
           {
            $q->select('id', 'owner_id', 'emailid', 'name');
           }
          ])->
          get();

In this way you can also get all of the columns of the related model if you have ever needed to.

通过这种方式,您还可以根据需要获取相关模型的所有列。

回答by Bogdan

In your controller you should be doing something like

在您的控制器中,您应该做类似的事情

App\Car::with('owner:id,name,email')->get();

Supposing that you have two models defined like below

假设你有两个模型定义如下

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Car extends Model
{
    protected $table = 'car';

    public function owner()
    {
        return $this->belongsTo('App\Owner', 'owner_id');
    }
}

and

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Owner extends Model
{
    protected $table = 'owner';

    public function car()
    {
        return $this->hasMany('App\Car', 'owner_id');
    }
}

and you have two tables something like:

你有两个表,比如:

owners: id | name | email | phone | other_columns...

and

cars: id | owner_id | make | color | other_columns...

Credits go to the docs: eloquent-relationships#eager-loadingscroll to Eager Loading Specific Columns

积分转到文档:eloquent-relationships#eager-loadingscroll to Eager Loading Specific Columns

回答by Shahrukh Anwar

The easiest thing you can do is go by the documentation and do the following thing for getting only specific columns without any extra line of code or closure. Follow steps,

您可以做的最简单的事情是查看文档并执行以下操作以仅获取特定列,而无需任何额外的代码行或闭包。按照步骤,

public function car(){
    return $this->hasOne('Car', 'id');
}

then when you eager load the relation select only selected columns

然后当您急切加载关系时,只选择选定的列

$owner = $this->owner
->where('id', 23)
->with('car:id,owner_id,emailid,name')   //no space after comma(, ) and id has to be selected otherwise it will give null

Hope this works, have a great day.

希望这有效,祝你有美好的一天。

回答by Shirjeel Ahmed Khan

Try WITH()& WHERE()conditions.

尝试WITH()WHERE()条件。

$user_id = 1; // for example

Post::with(array('user'=>function($query) use ($user_id ){
            $query->where('user_id','=',$user_id );
            $query->select('user_id','username');
        }))->get();