Laravel检查相关模型是否存在

我有一个口才的模型,其中有一个相关的模型:


public function option() {

    return $this->hasOne('RepairOption', 'repair_item_id');

}


public function setOptionArrayAttribute($values)

{

    $this->option->update($values);

}

创建模型时,它不一定具有相关的模型。更新时,可能会添加一个选项,也可能不会添加。


因此,我需要检查相关模型是否存在,以分别对其进行更新或创建:


$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());

    }

};

<related_model_exists>我要查找的代码在哪里。


翻过高山走不出你
浏览 943回答 3
3回答

白猪掌柜的

在php 7.2+中,您不能count在关系对象上使用,因此对于所有关系都没有一种万能的方法。使用查询方法代替@tremby,如下所示:$model->relation()->exists()适用于所有关系类型的通用解决方案(php 7.2之前的版本):if (count($model->relation)){&nbsp; // exists}由于动态属性返回Model或,因此这将适用于每个关系Collection。两者都实现ArrayAccess。所以它是这样的:单一的关系: hasOne / belongsTo/ morphTo/morphOne// no related model$model->relation; // nullcount($model->relation); // 0 evaluates to false// there is one$model->relation; // Eloquent Modelcount($model->relation); // 1 evaluates to true一对多关系: hasMany / belongsToMany/ morphMany/ morphToMany/morphedByMany// no related collection$model->relation; // Collection with 0 items evaluates to truecount($model->relation); // 0 evaluates to false// there are related models$model->relation; // Collection with 1 or more items, evaluates to true as wellcount($model->relation); // int > 0 that evaluates to true

拉风的咖菲猫

甲Relation对象穿过一个未知的方法调用口才查询生成器,其被设置为仅选择相关对象。该Builder进而将未知方法调用传递到其基础查询Builder。这意味着您可以直接从关系对象使用exists()or count()方法:$model->relation()->exists(); // bool: true if there is at least one row$model->relation()->count(); // int: number of related rows注意relation:后面的括号->relation()是一个函数调用(获取关系对象),->relation与之相反,Laravel为您设置了一个魔术属性获取器(获取相关对象)。count在关系对象上使用方法(即使用括号)将比这样做$model->relation->count()或count($model->relation)(除非该关系已被急切加载)要快得多,因为它运行计数查询而不是为任何相关对象提取所有数据从数据库中,只是为了计算它们。同样,使用exists也不需要提取模型数据。无论exists()和count()工作在我已经尝试了所有关系类型,所以至少belongsTo,hasOne,hasMany,和belongsToMany。

喵喵时光机

之后的PHP 7.1,接受的答案将不是对所有类型的关系的工作。因为根据类型的关系,Eloquent将返回a Collection,a Model或Null。并且在PHP 7.1 count(null)中将抛出一个error。因此,要检查该关系是否存在,可以使用:对于单一关系:例如hasOne和belongsToif(!is_null($model->relation)) {&nbsp; &nbsp;....}对于多重关系:例如:hasMany和belongsToManyif ($model->relation->isNotEmpty()) {&nbsp; &nbsp;....}
打开App,查看更多内容
随时随地看视频慕课网APP