Php 使用雄辩的ORM自定义方法链接?
这是我当前的查询:Php 使用雄辩的ORM自定义方法链接?,php,laravel,eloquent,Php,Laravel,Eloquent,这是我当前的查询: $cars = Cars::with('brand')->get(); $cars->map(function($cars){ $cars->fullName = $cars->brand->brand." ".$cars->name; //other manipulation... return $cars; }); 我想在模型中操纵我的集合,这样我就可以运行类似于$cars=cars::with('bran
$cars = Cars::with('brand')->get();
$cars->map(function($cars){
$cars->fullName = $cars->brand->brand." ".$cars->name;
//other manipulation...
return $cars;
});
我想在模型中操纵我的集合,这样我就可以运行类似于$cars=cars::with('brand')->getWithBrand()的东西代码>
如何才能做到这一点,这样我就不必每次运行查询时都编写映射函数了?在您的特定示例中,根本不需要使用map
来修改集合。可以使用定义数据库中不存在的模型的属性。在您的示例中,您将在车型上定义以下方法:
public function getFullNameAttribute($value)
{
// make sure brand exists first
if ($this->brand) {
return $this->brand->brand.' '.$this->name;
}
// default if brand doesn't exist
return $this->name;
}
class Cars extends Model
{
protected $appends = ['full_name'];
public function getFullNameAttribute($value)
{
// make sure brand exists first
if ($this->brand) {
return $this->brand->brand.' '.$this->name;
}
// default if brand doesn't exist
return $this->name;
}
}
通过在模型上定义该函数,每当您尝试使用full_name
属性时,都会调用该函数,如下代码所示:
$car = Cars::with('brand')->first();
// this will echo the result of the getFullNameAttribute method
echo $car->full_name;
编辑
如果您还希望此新属性自动显示在toArray()
或toJson()
输出中,您可以将该属性添加到车型的$appends
属性中:
public function getFullNameAttribute($value)
{
// make sure brand exists first
if ($this->brand) {
return $this->brand->brand.' '.$this->name;
}
// default if brand doesn't exist
return $this->name;
}
class Cars extends Model
{
protected $appends = ['full_name'];
public function getFullNameAttribute($value)
{
// make sure brand exists first
if ($this->brand) {
return $this->brand->brand.' '.$this->name;
}
// default if brand doesn't exist
return $this->name;
}
}
但是,请注意,自定义属性依赖于相关对象。因此,如果您在一组没有立即加载品牌
关系的汽车上意外调用toArray()
、toJson()
、toString()
等,这将导致N+1查询问题
例如:
// Bad: N+1 issue because each printed Car will execute a
// separate query to get its brand to output full_name.
echo Cars::get();
// Good: No N+1 issue because all brands are already loaded.
echo Cars::with('brand')->get();
在你的例子中,你的意思是$this而不是$cars吗?如果你使用$car->all(),我认为这是行不通的
或toArray()
@tgun926如果希望此属性显示在toArray()
或toJson()
输出中,可以将该属性添加到模型的$appends
属性中。我再次更新了代码以显示示例。