Laravel急切加载-仅加载特定列 [英] Laravel Eager Loading - Load only specific columns

查看:45
本文介绍了Laravel急切加载-仅加载特定列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在laravel中加载模型,但只返回某些列.我不希望显示整个渴望加载的表.

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.

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

我遇到以下错误:

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

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

推荐答案

使用select()方法:

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

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

Note: Remember to add the columns assigned to the foreign key matching both tables. For instance, in my example, I assumed a Owner has 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_id to the list of selected columns;

这篇关于Laravel急切加载-仅加载特定列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆