栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Laravel检查相关模型是否存在

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Laravel检查相关模型是否存在

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; // 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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/465829.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号