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?
I've added this method to the model that needs to be linked (in my case it is many-to-many relation):
ActiveQuery
hasexists()
method that does what you need. Let's assume you have aBook
class that is linked toAuthor
class. SoBook
hasgetAuthor()
method. Here's how you find out if related record exists:Note that
$book->author
returns an instance ofAuthor
(or an array if it's ahasMany
relation), whilegetAuthor()
returns anActiveQuery
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.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.