将方法添加到 Eloquent 关系
add method to Eloquent relation
我定义了这样的关系
class Contact extends Model
{
public function phones()
{
return $this->hasMany(Phones::class, "contact_id");
}
}
然后,在ContactsController
,我可以访问联系人的电话
$contact->phones()
其中 returns Illuminate\Database\Eloquent\Relations\HasMany
。现在,我想对该关系(或任何类似的关系)做一些事情,假设我想执行一些验证。我想做这样的事情:
$contact->phones()->doSomething();
并且在 doSomething()
中可以访问 parent(联系人)和关系(电话)。我尝试向模型添加特征,但出现错误
Call to undefined method
Illuminate\Database\Eloquent\Relations\HasMany::doSomething()
那么,有没有可能达到我想要的效果呢?我知道我可以创建一个方法并将 $contact->phones()
作为参数传递并使用它,但我很好奇我的方法是否可行
由于 HasMany
关系 class 具有 Macroable
特征,您可以扩展它以添加自定义方法。
在AppServiceProvider
中添加开机方式:
HasMany::macro('yourCustomMethod', function($yourParameters) {
// Laravel binds $this to context of macro, not the class where you defined it.
return $this;
});
您将能够做到这一点:
$contact->phones()->yourCustomMethod();
我定义了这样的关系
class Contact extends Model
{
public function phones()
{
return $this->hasMany(Phones::class, "contact_id");
}
}
然后,在ContactsController
,我可以访问联系人的电话
$contact->phones()
其中 returns Illuminate\Database\Eloquent\Relations\HasMany
。现在,我想对该关系(或任何类似的关系)做一些事情,假设我想执行一些验证。我想做这样的事情:
$contact->phones()->doSomething();
并且在 doSomething()
中可以访问 parent(联系人)和关系(电话)。我尝试向模型添加特征,但出现错误
Call to undefined method Illuminate\Database\Eloquent\Relations\HasMany::doSomething()
那么,有没有可能达到我想要的效果呢?我知道我可以创建一个方法并将 $contact->phones()
作为参数传递并使用它,但我很好奇我的方法是否可行
由于 HasMany
关系 class 具有 Macroable
特征,您可以扩展它以添加自定义方法。
在AppServiceProvider
中添加开机方式:
HasMany::macro('yourCustomMethod', function($yourParameters) {
// Laravel binds $this to context of macro, not the class where you defined it.
return $this;
});
您将能够做到这一点:
$contact->phones()->yourCustomMethod();