只是想知道是否可能在Eloquent中存在某种关系的findOrNew (如果关系不存在,则附加新的模型实例)?
意思是:假设我们有设备和规格表。设备属于规范。Specification_id是一个FK (我知道这不是最好的方法,但我有以前的程序员留下的类似的东西)。在id 11下,我们有一个没有规格的设备,但无论如何我们都必须为用户显示它。
$device = Device::find(11);
echo $device->specification->cpu;在这种情况下,它将抛出一个错误,因为规范将是空-它对于id为11的设备不存在。
我知道我可以先检查它是否存在,但有很多类似的线路和应用程序是相当大的。我要把它从Kohana移到Laravel它在Kohana中工作,因为空对象被加载,然后第二行只返回null。对于Laravel,我可以检查关系是否存在,然后加载新模型,但我很好奇,是否有其他更好的方法?
发布于 2015-12-30 00:27:27
我会这样在Device模型中创建额外的方法:
public function getSpecification()
{
if ($device->specification) {
return $device->specification;
}
return Specification::find(20); // some default specification
// or
// return new Specification(['cpu' => 'Not provided']);
}现在你可以这样使用它:
$device = Device::find(11);
$device->getSpecification()->cpu;当然,这取决于您需要如何使用它。如果你有很多属性,你应该为object只运行一次这个方法,这样就不会运行多个查询,如果你想将它用于大型集合,你也应该重新考虑如何改进以减少数据库查询。
发布于 2015-12-30 00:43:31
这并不能完全按照您的请求创建相关的对象,但是为了在没有相关模型的情况下输出数据或复制Kohana的空输出,我倾向于使用data_get()或object_get()帮助器来实现此目的。
$device = Device::find(11);
echo object_get($device->specification, 'cpu');
// You could probably do this too (untested)
echo object_get($device, 'specification.cpu');看了一下之后,您可以覆盖Illuminate\Database\Eloquent\Model中的getRelationshipFromMethod()方法
protected function getRelationshipFromMethod($method)
{
// Different relationships return different types of data so
// tweak this as necessary. In theory you only care if the relationship
// type is a single entity rather than a collection.
$results = parent::getRelationshipFromMethod($method);
if ($results instanceOf Illuminate\Database\Eloquent\Collection) {
return $results;
}
// Generate a null value for any missing attributes
// PHP7 anonymous class. Return a real class < 7.0
return $this->relations[$method] = new class {
public function __get($attribute) {
return null;
}
};
// Or perhaps actually create a relationship with a specification
$this->relations[$method] = Specification::where('default', true)->first();
$this->specification()->associate($this->relations[$method]);
return $this->relations[$method];
}https://stackoverflow.com/questions/34514910
复制相似问题