检查模型是否存在多对多关系的最佳方法 [英] Best way to check if a Model exists in a many-to-many relationship
本文介绍了检查模型是否存在多对多关系的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些数据发布到服务器,并且正在基于该数据(id)检索一个Player
.我正在使用以下代码:
I have some data being posted to the server and am retrieving a Player
based on that data (an id). I am using the following code:
$player = Player::findOrFail($player_data['id']);
但是,我要检查此Player
是否属于特定的Team
-belongsToMany
关系.
However, I want to check that this Player
belongs to a specific Team
- a belongsToMany
relationship.
有没有比以下更好的方法了?
Is there a better way than something like:
if (! count($player->team()->find($teamId))) {
// exit early, form may have been 'hacked'
abort(404);
}
?
team()
而不是teams()
,即使它是多对多的.
team()
and not teams()
, even though its a many-to-many.
推荐答案
使用 contains()
方法:
$player->team->contains($teamId);
contains方法确定集合是否包含给定项
The contains method determines whether the collection contains a given item
这篇关于检查模型是否存在多对多关系的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文