egor lostparadise
egor lostparadise

Reputation: 11

Create relation hasMany() with composite field

Have the relation in model Product :

public function getDiscount()
{
    return $this->hasMany(Discount::className(), ['id' => 'available_discount']);
}

Model has field available_discount, that stores data as 1;2;3, where 1;2;3 is discount ids.

Query Product::find()->joinWith('discount d')->where(['d.id' => [1,2,3]])->all()return products with key discount = [].

How i can return discounts as relation with ID 1, 2, 3 ?

Upvotes: 1

Views: 81

Answers (1)

t6nnp6nn
t6nnp6nn

Reputation: 317

Try this:

public function getDiscounts()
{
    $idsAsArray = explode(';', $this->available_discount);
    $query = Discount::find()->where(['id' => $idsAsArray]);
    $query->multiple = true;
    return $query;
}

And then get them via:

$product->discounts; // returns Discount[]
$product->getDiscounts()->count(); // gets the count of discount models.

Upvotes: 1

Related Questions