For example I have an ActiveRecord ‘Comment’ with $reference_id and $reference_model.
$reference_model is set either to ‘Post’ or ‘Product’. $reference_id is corresponding either the post-id or product-id.
I would like to have two hasOne relations in Comment, but only on can be true at a time.
How can this be done?
I tried something like:
public function getPost()
{
if ($this->reference_model == 'Post') {
return $this->hasOne(Post::className(), ['id' => 'reference_id']);
}
}
public function getProduct()
{
if ($this->reference_model == 'Product') {
return $this->hasOne(Product::className(), ['id' => 'reference_id']);
}
}
But $this (Comment) is empty at the time when the relation is built.
In native SQL I would have done this:
SELECT comment.id, post.name
FROM comment
LEFT JOIN post ON (comment.reference_id = post.id AND comment.reference_model = 'Post')
post.name would have been NULL if it is a comment from Product.
How can I do this in Yii2?