Laravel 检查相关模型是否存在 [英] Laravel Check If Related Model Exists
问题描述
我有一个 Eloquent 模型,它有一个相关的模型:
I have an Eloquent model which has a related model:
public function option() {
return $this->hasOne('RepairOption', 'repair_item_id');
}
public function setOptionArrayAttribute($values)
{
$this->option->update($values);
}
当我创建模型时,它不一定有相关模型.当我更新它时,我可能会添加一个选项,也可能不添加.
When I create the model, it does not necessarily have a related model. When I update it, I might add an option, or not.
所以我需要检查相关模型是否存在,分别更新它或创建它:
So I need to check if the related model exists, to either update it, or create it, respectively:
$model = RepairItem::find($id);
if (Input::has('option')) {
if (<related_model_exists>) {
$option = new RepairOption(Input::get('option'));
$option->repairItem()->associate($model);
$option->save();
$model->fill(Input::except('option');
} else {
$model->update(Input::all());
}
};
其中
是我要查找的代码.
Where <related_model_exists>
is the code I am looking for.
推荐答案
在 php 7.2+ 中你不能在关系对象上使用 count
,所以没有一个-适合所有关系的所有方法.使用下面提供的@tremby 查询方法:
In php 7.2+ you can't use count
on the relation object, so there's no one-fits-all method for all relations. Use query method instead as @tremby provided below:
$model->relation()->exists()
<小时>
适用于所有关系类型的通用解决方案(pre php 7.2):
if (count($model->relation))
{
// exists
}
这将适用于每个关系,因为动态属性返回 Model
或 Collection
.两者都实现了ArrayAccess
.
This will work for every relation since dynamic properties return Model
or Collection
. Both implement ArrayAccess
.
事情是这样的:
单一关系: hasOne
/belongsTo
/morphTo
/morphOne
>
// no related model
$model->relation; // null
count($model->relation); // 0 evaluates to false
// there is one
$model->relation; // Eloquent Model
count($model->relation); // 1 evaluates to true
对多关系: hasMany
/belongsToMany
/morphMany
/morphToMany
/morphedByMany
// no related collection
$model->relation; // Collection with 0 items evaluates to true
count($model->relation); // 0 evaluates to false
// there are related models
$model->relation; // Collection with 1 or more items, evaluates to true as well
count($model->relation); // int > 0 that evaluates to true
这篇关于Laravel 检查相关模型是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!