条件与 HasOne laravel

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38369905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:09:24  来源:igfitidea点击:

where condition with HasOne laravel

laravelhas-one

提问by Harman

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

现在我想要 Picture.picture_status = 1 和 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

但是如果条件不适用于图片表,我如何在两个表上实施和条件

回答by ClearBoth

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

有时您可能希望预先加载关系,但也为预先加载查询指定额外的查询约束 https://laravel.com/docs/5.2/eloquent-relationships#constraining-eager-loads

回答by Ilya Yaremchuk

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

回答by Mehmet

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

回答by Alex Bachynskyi

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

万一有人仍然偶然发现这个问题。检索正确记录的最佳方法是将 Laravel Query Builder 与 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

您可以在https://laravel.com/docs/6.x/queries#joins了解更多信息