Yii2如何检查两个模型是否已经链接 [英] Yii2 how to check if two models are already linked

查看:162
本文介绍了Yii2如何检查两个模型是否已经链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个通过联结表关联的模型.

I have two models related through a junction table.

$model->link()是用于建立两个模型之间关系的方法.基本上,用两个模型的对应键填充联结表.

$model->link() is the method used to establish the relationship between the two models. It basically populates the junction table with the corresponding keys of both models.

如果两个模型被链接,而我尝试再次链接它们,则会出现错误,因为键对已经存在于联结表中.然后,在尝试链接模型之前,我需要检查此关系是否存在.

If two models are linked and I try to link them again, there will be an error because the key pair already exists in the junction table. Then I'd need to check if this relation exists before attempting to link the models.

我想我可以为联结表创建一个模型并查询正确的记录.该查询的结果将告诉我是否需要执行链接.

I think I could just create a model for the junction table and query for the proper record. The result of that query would tell if I need to perform the link.

问题是:

是否有使用某些yii内置方法执行此检查的简便方法?

Is there a short and easy way to perform this check, using some yii built-in method?

推荐答案

ActiveQuery具有实现所需功能的exists()方法.假设您有一个链接到Author类的Book类.因此Book具有getAuthor()方法.查找相关记录是否存在的方法如下:

ActiveQuery has exists() method that does what you need. Let's assume you have a Book class that is linked to Author class. So Book has getAuthor() method. Here's how you find out if related record exists:

$book->getAuthor()->exists();

请注意,$book->author返回Author的实例(如果是hasMany关系,则返回数组),而getAuthor()返回ActiveQuery实例.

Note that $book->author returns an instance of Author (or an array if it's a hasMany relation), while getAuthor() returns an ActiveQuery instance.

执行exists()仍然像$book->author一样运行一个SQL查询,但是该查询比实际获取数据和创建相应模型的效率更高.

Executing exists() still runs one SQL query just like $book->author would, but that query is more efficient than actually fetching the data and creating the corresponding model.

另一方面,在很多情况下,性能的提高是微不足道的,因此您只需运行isset($book->author)并完成它即可.

On the other hand, in many cases the performance improvement is negligible, so you can just run isset($book->author) and be done with it.

这篇关于Yii2如何检查两个模型是否已经链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆