为了账号安全,请及时绑定邮箱和手机立即绑定

Laravel检查相关模型是否存在

Laravel检查相关模型是否存在

PHP
翻过高山走不出你 2019-11-26 14:49:11
我有一个口才的模型,其中有一个相关的模型: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>我要查找的代码在哪里。
查看完整描述

3 回答

?
白猪掌柜的

TA贡献1893条经验 获得超10个赞

在php 7.2+中,您不能count在关系对象上使用,因此对于所有关系都没有一种万能的方法。使用查询方法代替@tremby,如下所示:


$model->relation()->exists()

适用于所有关系类型的通用解决方案(php 7.2之前的版本):


if (count($model->relation))

{

  // exists

}

由于动态属性返回Model或,因此这将适用于每个关系Collection。两者都实现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


查看完整回答
反对 回复 2019-11-26
?
拉风的咖菲猫

TA贡献1995条经验 获得超2个赞

甲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。


查看完整回答
反对 回复 2019-11-26
?
喵喵时光机

TA贡献1846条经验 获得超7个赞

之后的PHP 7.1,接受的答案将不是对所有类型的关系的工作。


因为根据类型的关系,Eloquent将返回a Collection,a Model或Null。并且在PHP 7.1 count(null)中将抛出一个error。


因此,要检查该关系是否存在,可以使用:


对于单一关系:例如hasOne和belongsTo


if(!is_null($model->relation)) {

   ....

}

对于多重关系:例如:hasMany和belongsToMany


if ($model->relation->isNotEmpty()) {

   ....

}


查看完整回答
反对 回复 2019-11-26
  • 3 回答
  • 0 关注
  • 942 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信