简体   繁体   中英

Laravel join with sub query

I have two models User and Address, one user can have many addresses but I want to fetch only which is primary(where primary=true)

this is what I have tried, and I am getting multiple users in the list

$users = User::join('addresses', 'addresses.user_id', 'users.id')
             ->select('name','phone_number','address','landmark','city','state','pincode','users.status')
             ->get();

I tried this too but I am not getting any data

$users = User::join('addresses', 'addresses.user_id', 'users.id')
             ->where('addresses.primary', true)
             ->select('name','phone_number','address','landmark','city','state','pincode','users.status')
             ->get();

thank you

Collection {#375 ▼
  #items: array:8 [▼
    0 => User {#376 ▶}
    1 => User {#377 ▼
      #attributes: array:9 [▼
        "name" => "Colin Sushanth"
        "phone_number" => "9987217545"
        "address" => "2nd Cross 3rd street, y this is my address"
        "landmark" => "Near the address"
        "city" => "Mangalore"
        "state" => "Karnataka"
        "pincode" => 575002
        "status" => "valid"
        "primary" => "true"
      ]
    }
    2 => User {#378 ▶}
  ]
}

You should try this:

$users = User::join('addresses', 'addresses.user_id', 'users.id')
             ->where('addresses.primary','=',1)
             ->select('name','phone_number','address','landmark','city','state','pincode','users.status')
             ->get();

Or:

$users = User::join('addresses', 'addresses.user_id', 'users.id')
                 ->where('addresses.primary','=',true)
                 ->select('name','phone_number','address','landmark','city','state','pincode','users.status')
                 ->get();

Updated answer

Blade file:

@if(isset($users))

  @foreach($users as $user)

    @if($user->primary === 'true')

        //Your code

    @endif

  @endforeach

@endif

I would do it using eloquent models

So you would u do

User::whereHas('primary')->pluck('name','phone_number','address','landmark','city','state','pincode','users.status')

and your model will look like this

 public function addresses()
    {
        return $this->belongsTo('App\Models\Address');
    }

    public function primary()
    {
        return $this->addresses->primary == true;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM