Umair Zahid
Umair Zahid

Reputation: 441

Laravel eloquent Relationship Query

My database schema is

links:
 id      status        user_id       url
  1         1            1            something
  2         1            1            something
  3         1            1            something

links_type:
 id         link_id      links_type
  1            1            external
  2            1            external
  3            1            internal
  4            1            external
  5            2            internal
  6            2            external
  7            2            internal
  8            2            external

i want to take data of all links which status is 1 and user_id is 1 and count external and internal links and which external count is >2.

by using laravel 5.2 eloquent.

result should be like this from data given

  id     status   user_id     url       external_links     internal_links
   1        1       1       something         3                   1

Upvotes: 1

Views: 474

Answers (3)

Ata
Ata

Reputation: 312

maybe this could work.

before you must create hasMany relation for Link and name as type

$links = Link::where('status', 1)
    ->wherer('user_id', 1)
    ->whereHas('type', function($query) {
        $query->where(
            $query->where('links_type', 'external')->count(), '>', 2
        );
    })
    ->get();

Upvotes: 0

nextt1
nextt1

Reputation: 3988

Just define this relationship in Link Model

public function link_type()
{
    return $this->hasMany('App\linkType');

}

and use this query

Link::where('status','=','1')->where('user_id','=','1')->has('link_type','>', '2')->with('link_type')->get();

Upvotes: 1

Tim L
Tim L

Reputation: 175

If you already have the right migrations with fk's and Models following code should be working:

$links = Link::where('status','=','1')->where('user_id','=','1') ->whereHas('links_type',function ($query) { $query->whereNotIn('external_count', [0,1]); })->get();

Probably should add with('links_type') for eager_loading (N+1 problem):

$links = Link::with('links_type')->where('status','=','1')->where('user_id','=','1') ->whereHas('links_type',function ($query) { $query->whereNotIn('external_count', [0,1]); })->get();

Upvotes: 0

Related Questions