14

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

Harman
  • 1,703
  • 5
  • 22
  • 40

5 Answers5

14
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();
Mehmet
  • 170
  • 1
  • 7
  • 12
    There's no need to append `first()` at the end. – user8555937 Dec 29 '20 at 09:26
  • 2
    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`. – ibnɘꟻ Jun 19 '21 at 04:45
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

ClearBoth
  • 2,235
  • 2
  • 18
  • 24
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();
    }
}
Ilya Yaremchuk
  • 2,007
  • 2
  • 19
  • 36
0

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

0

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);
        });
}
layouteam
  • 51
  • 6