[英]return if id not null, laravel elequent
I have connected tables with a hasMany
& belongsTo
relationship.我已经用
hasMany
& belongsTo
关系连接了表。
Bridal Model:新娘Model:
public function plans()
{
return $this->hasMany("App\Plan");
}
Plan Model:计划 Model:
public function bridal()
{
return $this->belongsTo("App\Bridal");
}
And I have an query that returns those data to endpoint.我有一个查询,将这些数据返回到端点。
public function bridal()
{
$bridals = Bridal::with(["plans" => function($query){
$query->orderBy("plans.plan_price");
}])
->groupBy("place_name")
->get();
return $bridals;
}
Everything is fine, except one thing.一切都很好,除了一件事。 In Bridal table some of ID doesn't have plan.
在新娘表中,一些 ID 没有计划。 So when I return datas, some of
bridal id
comes with an empty Plans
array.所以当我返回数据时,一些
bridal id
带有一个空的Plans
数组。
I want to prevent that.我想阻止这种情况。 If a
bridal id
doesn't have a plan, then I don't want to return that bridal id.如果
bridal id
没有计划,那么我不想归还那个新娘身份证。 How can I achieve what I want here?我怎样才能在这里实现我想要的?
You can use Has .您可以使用Has 。 If you just use
has('relation')
that means you only want to get the models that have at least one related model in this relation.如果您只使用
has('relation')
,则意味着您只想获取在此关系中至少具有一个相关 model 的模型。
$bridals = Bridal::with(["plans" => function($query){
$query->orderBy("plans.plan_price");
}])->has('plans')
->groupBy("place_name")
->get();
Add whereHas() in your query: so you will get bridal records which has plans在您的查询中添加 whereHas() :这样您将获得有计划的新娘记录
$bridals = Bridal::with(["plans" => function($query){
$query->orderBy("plans.plan_price");
}])
->whereHas('plans')
->groupBy("place_name")
->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.