where condition with HasOne laravel
Asked Answered
U

5

15

In login model I have implement relation with picture table

function picture () {
   return $this->hasOne('App\Picture');
}

Now I want data where Picture.picture_status = 1 and User.user_status = 1

Login::with('picture')->where('picture_status', 1)->where('user_status',1);

but where condition is not working with picture table, how can i implement and condition on both table

Unwilling answered 14/7, 2016 at 9:3 Comment(0)
T
15
class Login extends Model
{
    protected $primaryKey = 'id';

    function picture () {
       return $this->hasOne('App\Picture', 'id', 'user_id')->where('picture_status', 1)->where('user_status',1)->first();
    }
}

You can call like this;

$usersWithProfilePictures = Login::with('picture')->get();
Trichoid answered 14/5, 2019 at 21:26 Comment(2)
There's no need to append first() at the end.Erotomania
If you add first() at the end, $login->picture will return null. Since you treat picture as a method, not a model property. You should remove the first(), and then you can call it just like model property, $login->picture.Mckeown
S
9

This should do it:

Login::with(['picture' => function ($query) {
    $query->where('picture_status', 1)->where('user_status',1);
}])->get();

Sometimes you may wish to eager load a relationship, but also specify additional query constraints for the eager loading query https://laravel.com/docs/5.2/eloquent-relationships#constraining-eager-loads

Saharan answered 14/7, 2016 at 10:20 Comment(0)
X
2
class Login extends Model
{
    protected $primaryKey = 'id';

    function picture () {
       return $this->hasOne('App\Picture', 'id', 'user_id');
    }

    ................
    public function myF(){
         self::with('picture')->where('picture_status', 1)->where('user_status',1)->get();
    }
}
Xerosis answered 14/7, 2016 at 10:24 Comment(0)
A
1

In case someone still stumbles upon this problem. The best way to retrieve correct records would be to use Laravel Query Builder with join:

$logins = DB::table('logins')
            ->join('pictures', 'logins.id', '=', 'pictures.login_id')
            ->select('logins.*', 'pictures.status')
            ->where('logins.status', 1)
            ->where('pictures.status', 1)
            ->get();

You can learn more at https://laravel.com/docs/6.x/queries#joins

Agna answered 23/4, 2020 at 8:41 Comment(0)
S
1

You have to use ofMany Laravel function wich means the Model has one of many

function picture()
{
    return $this->hasOne('App\Picture', 'id', 'user_id')->ofMany(
        function ($query) {
            return $query->where('picture_status', 1)->where('user_status', 1);
        });
}
Softwood answered 23/1, 2023 at 21:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.