Jaeyoung Heo
Jaeyoung Heo

Reputation: 87

Laravel Eloquent relations condition

I have two models in Laravel : Article and Relatedproduct.

Article class

public function related_products()
{
    return $this->hasMany(\App\Models\ArticleProduct::class, 'article_id', 'id');
}

ArticleProduct class

public function related_product()
{
    return $this->belongsTo(\App\Models\Product::class, 'product_id', 'id');
}

I got Article and want to get related_products where status is set as 1.

I was able to get them as following code

foreach ($article->related_products as $i => $product) {
    if ($product->related_product->status == 1) {
        array_push($related_tour, $product->related_product);
    }
}

is there better way to achieve this?

Upvotes: 0

Views: 77

Answers (2)

Thai Nguyen Hung
Thai Nguyen Hung

Reputation: 1212

Try this one:

public function relatedTours()
{
    return $this->belongsTo(\App\Models\Product::class, 'product_id', 'id')
        ->where('status', 1);
}

In your logic:

$article->relatedTours

Upvotes: 0

Manuel Eduardo Romero
Manuel Eduardo Romero

Reputation: 891

You can use ->where clause too with belongTo, eg.

public function related_product()
{
    return $this->belongsTo('App\Models\Product', 'product_id', 'id')
        ->where('status', true);
}

Please try this and let me know how it works :)

Upvotes: 0

Related Questions