Yii2 how to check if two models are already linked

大城市里の小女人 提交于 2019-12-10 07:46:42

问题


I have two models related through a junction table.

$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.

The question is:

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


回答1:


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

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

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.

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.




回答2:


I think that easiest way is just to call the relation method. With model Foo and relation method for model Bar getBar() (defined with via junction table) (new Foo)->bar is null if there is no link. Of course this is valid in case of one-to-one relation. For one-to-many you have to check result array.




回答3:


I've added this method to the model that needs to be linked (in my case it is many-to-many relation):

/**
 * @inheritdoc
 */
 public function link($name, $model, $extraColumns = [])
 {
     $exists = $this->getJunctionModel()
         ->where(['other_model_id' => $model->primaryKey])
         ->exists();

     if (!$exists) {
         parent::link($name, $model, $extraColumns);
     }
 }


来源:https://stackoverflow.com/questions/33574197/yii2-how-to-check-if-two-models-are-already-linked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!