Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 how to check if two models are already linked

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?

like image 766
Arge Avatar asked Mar 14 '23 06:03

Arge


2 Answers

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.

like image 187
Beowulfenator Avatar answered Mar 20 '23 21:03

Beowulfenator


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.

like image 29
Bizley Avatar answered Mar 20 '23 19:03

Bizley