Laravel Eager Loading - 仅加载特定列

问题描述 投票:32回答:3

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

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

我收到以下错误:

log.ERROR:异常'Symfony \ Component \ Debug \ Exception \ FatalErrorException',带有消息'调用未定义的方法Illuminate \ Database \ Eloquent \ Collection :: getAndResetWheres()'

php laravel laravel-4
3个回答
56
投票

利用select()方法:

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

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


12
投票

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

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

通过这种方式,您还可以获得相关模型的所有列。


6
投票

在你的控制器中你应该做的事情

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

假设您有两个定义如下的模型

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

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

你有两个表,如:

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

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

积分转到文档:eloquent-relationships#eager-loading滚动到Eager加载特定列

© www.soinside.com 2019 - 2024. All rights reserved.