问题
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