Yii2 how to check if two models are connected

I have two models connected through a connection table.

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

If the two models are connected and I try to connect them again, an error will occur because a key pair already exists in the connection table. Then I will need to check if this relationship exists before trying to link the models.

I think that I could just create a model for the connection table and request the correct entry. The result of this query will tell me whether I need to follow the link.

The question arises:

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

+4
source share
3 answers

ActiveQueryhas a method exists()that does what you need. Suppose you have a class Bookassociated with a class Author. So, Bookhas a method getAuthor(). Here you will find out if the corresponding entry exists:

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

Note that it $book->authorreturns an instance Author(or an array, if this is a relation hasMany), but getAuthor()returns an instance ActiveQuery.

Execution exists()still runs a single SQL query exactly the same as $book->author, but this query is more efficient than actually selecting the data and creating the appropriate model.

, , isset($book->author) .

+3

, - . Foo Bar getBar() ( ) (new Foo) → bar null, . , - . -- .

+2

, ( --):

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

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

Source: https://habr.com/ru/post/1614791/


All Articles