[英]Eloquent - using a closure with a relationship
I have this problem with Laravel Eloquent. Laravel Eloquent 有这个问题。 I have two models - for simplicity's sake named:
我有两个模型 - 为简单起见,命名为:
I need to return all B records filtered by these conditions:我需要返回由这些条件过滤的所有 B 记录:
I want to do this by passing in a closure.我想通过传入一个闭包来做到这一点。 I searched through the laravel documentation on models:
我搜索了有关模型的 laravel 文档:
https://laravel.com/docs/7.x/eloquent https://laravel.com/docs/7.x/eloquent
https://laravel.com/docs/7.x/eloquent-relationships https://laravel.com/docs/7.x/eloquent-relationships
and found these examples, but how do I put this together?并找到了这些例子,但是我该如何把它们放在一起呢?
public function user()
{
return $this->belongsTo('App\User')->withDefault(function ($user, $post) {
$user->name = 'Guest Author';
});
}
function (Builder $builder) {
$builder->where('age', '>', 200);
}
You can do it using whereHas
but first you need to define the relationship in your models like so:您可以使用
whereHas
来做到这一点,但首先您需要在模型中定义关系,如下所示:
A Model A Model
class A extends Model
{
/**
* Get all B for the A.
*/
public function b()
{
return $this->hasMany(B::class);
}
}
B Model B Model
class B extends Model
{
/**
* Get the B's A.
*/
public function a()
{
return $this->belongsTo(A::class);
}
}
Now after we defined the relationships just use whereHas
with a Closure to check for extra conditions:现在,在我们定义了关系之后,只需使用带有闭包的
whereHas
来检查额外的条件:
$allB = B::whereHas('a', function (Builder $query) {
$query->where('A.name', $givenName);
})->where('created_at','>=',$givenDate)->get();
You need to write this on A model你需要在 A model 上写这个
class A extends Model
{
public function aToB()
{
return $this->hasMany('App\B', 'a_id', 'id');
}
}
Then you need to write the query然后你需要编写查询
$userData = A::where('name', $givenName)->with('aToB');
$userData = $userData->whereHas('aToB', function($query) use($givenDate){
$query->whereDate('created_at', date('Y-m-d', strtotime($givenDate)));
});
$userData = $userData->get();
dd($userData->aToB);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.