我用laravel设计了一个小数据库,有一个替换模型中的值的问题。
我的步骤如下。有两个有价值的基础,比如汽车品牌,还有一个是车主基础。相应地,第一基座具有如下形式
Id, description
7, bmw
9, audi第二个
Id, ownername, brandid
1, John, 7
2, leo, 9我替换了模板中的数据,给出了通过$owners ->$owners()方法获得的所有数组;如何正确地将品牌的id替换为其描述以获得2, leo, audi?谢谢
发布于 2017-03-27 10:52:37
在所有者模型中创建关系
public function brand() {
return $this->belongsTo(Brand::class, 'brandid');
}然后,如果您获得其中的一个,则在模板中调用该关系
$owner = Owner::find(1);
//in template
{{ $owner->brand->description }} //echo 'bmw' because owner 1 has 'brandid' 7如果你有很多所有者,你可以使用一个循环
$owners = Owner::get();
//in template
@foreach($owners as $owner)
{{ $owner->brand->description }}
@endforeach然而,在foreach循环中,如果您有1000个用户,您将进行1000次查询。如果你只使用少量的用户,这是可以的。但对于大数据集,急切的加载所有者和品牌
$owners = Owner::with('brand')->get();foreach保持不变,但只有2个查询,而不是1000个
发布于 2017-03-27 11:03:34
首先,创建关系:
public function brand()
{
return $this->belongsTo('App\Brand');
}其次,指定被自动加载的关系:
$owners = App\Owner::with('brand')->get();现在,您可以在刀片式服务器或其他地方使用结果:
foreach ($owners as $owner) {
echo $owner->brand->description;
}https://stackoverflow.com/questions/43037124
复制相似问题