where condition with HasOne laravel

霸气de小男生 提交于 2020-01-03 19:57:32

问题


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


回答1:


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




回答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();
    }
}



回答3:


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();


来源:https://stackoverflow.com/questions/38369905/where-condition-with-hasone-laravel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!