binggle's avatar

how to get model with self row condition ?

I have Two model , Client / Banner which relationship is BelogsTo / HasMany relation.

class Client extends Model
{
    public function banners()
    {
        return $this->hasMany(Banner::class);
    }
}

class Banner extends Model
{
    public function client()
    {
        return $this->belongsTo(Client::class);
    }
}

But the banners table has these fields.

id, client_id, banner_type, ...

And banner_type is either 1 or 2.

I get Client in controller with `banners' // in Controller

$client = Client::query()
        ->with('banners')
        ->find(1);

What I want to do is to get the banners where banner_type is 1 or 2.

How can I get this ?

$client->banners would get two row.

But I want to get only one row when banner_type is 1 or 2.

0 likes
2 replies
LaryAI's avatar
Level 58

You can use the whereHas method to filter the banners based on the banner_type field.

$client = Client::query()
    ->with(['banners' => function ($query) {
        $query->where('banner_type', 1)->orWhere('banner_type', 2);
    }])
    ->find(1);

This will return the $client object with the banners relationship filtered to only include banners with banner_type of 1 or 2.

binggle's avatar

@LaryAI

no answer.

It should be used in view as like this.

<tr>
    <td >{{ $item->banners->where('banner_type', 1)}}</td>
    <td >{{ $item->banners->where('banner_type', 2)}}</td>
</tr>

Please or to participate in this conversation.