PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 21, 2022

[FIXED] How to use constant in the ON condition in Yii2 hasMany relation

 October 21, 2022     has-many, polymorphic-associations, relation, yii2     No comments   

Issue

I try to create a polymorphic association, what is common in Rails but unfortunately not in Yii2. As part of the implementation I need to define the relation:

public function getImages()
{
   return $this->hasMany(RecipeImage::className(), 
       ['imageable_id' => 'id', 'imageable_type' => 'Person']);
}

But this doesn't work, because 'Person' is treated as an attribute of the current model, but it is a constant (class name for the polymorphic association).

If I try to use 'andWhere' it adds the condition of course in a WHERE clause instead of the ON clause, causing that only records with existing image returned.

public function getImages()
{
   return $this->hasMany(RecipeImage::className(), ['imageable_id' => 'id'])->
       andWhere(['imageable_type' => 'Ingredient']);
}

How can I define the relation? There is no andOn method.


Solution

In this case you can modify ON condition with andOnCondition method:

public function getImages()
{
    return $this->hasMany(RecipeImage::className(), ['imageable_id' => 'id'])
        ->andOnCondition(['imageable_type' => 'Person']);
}

Official docs:

  • andOnCondition:


Answered By - arogachev
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing