Yii2 how to check if two models are already linked

試著忘記壹切 提交于 2019-12-05 15:14:40

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.

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.

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