【发布时间】:2019-12-26 06:25:18
【问题描述】:
我想显示使用 count 函数的公司的产品数量,但它返回 0 为什么?
关系的真正语法是什么?
以及如何从模型的函数中获取 sql 查询?
Agent_Company.php
class Agent_Company extends Model
{
//
protected $table='agent_companies';
protected $primaryKey='id';
protected $fillable=['companyName','description','id_image'];
public function products(){
return $this->hasMany('App\Product','id','id_company');
}
public function image(){
return $this->belongsTo('App\Image','id_image');
}
}
Product.php
class Product extends Model
{
//
protected $table='products';
protected $primaryKey='id';
protected $fillable=[
'product','video','id_company','id_image',
];
public function Image(){
return $this->belongsTo('App\Image');
}
public function Agent_Company(){
return $this->belongsTo('App\Agent_Company','id_company','id');
}
}
有风景:
<div class="container">
{{$agent_Company->links()}}
<div class="row" id="company">
@foreach($agent_Company as $item)
<div class="card col-md-4" style="width: 300px; max-height: 500px;">
<div class="card-header">
<h2>{{$item->companyName}}</h2>
</div>
<img src="{{'agent_Companye_Images/'.$item->image->image}}" class="card-img-top"
alt="{{$item->image->alt}}" style="width: 300px; height: 300px">
<div class="card-body" style="overflow:auto">
<h5 class="card-title">Product:{{DD($item->Products->count())}}</h5>
<span class="card-title">
<a href="" class=" btn btn-primary"> Go to Company</a>
{{$item->description}}
</span>
</div>
</div>
@endforeach
</div>
</div>
【问题讨论】:
-
如果您不急于加载您的
products关系,那么计数将是0,因为您计算的是加载 产品关系的数量,而不是产品关系的数量(存储在数据库中)。 -
所以..?我应该改变什么?和谢谢
-
在您的控制器中,急切地加载您的产品关系。例如:
AgentCompany::with('products')->findOrFail(1)
标签: php laravel eloquent relationship eager-loading