Laravel 5. findOrNew用于关系

时间:2015-12-29 16:18:39

标签: php laravel laravel-5 eloquent

只是想知道是否有可能在Eloquent中存在某种关系的findOrNew(如果关系不存在则附加新的模型实例)?

这意味着什么: 可以说我们有设备和规格表。设备属于规范。 Specification_id是一个FK(知道这不是最好的方法,但我之前的程序员留下了这样的东西)。在id 11下,我们的设备没有规格,但我们必须为用户显示它。

$device = Device::find(11);
echo $device->specification->cpu;

在这种情况下,它会抛出一个错误,因为规范将为null - 对于ID为11的设备不存在。

知道我可以先检查它是否存在,但有很多类似的线和应用程序相当大。我需要把它从Kohana搬到Laravel。它在Kohana中工作,因为然后加载空对象,第二行只返回null。对于Laravel,我可以检查是否存在关系并加载新模型然后我很好奇,如果可能还有其他更好的方法吗?

2 个答案:

答案 0 :(得分:2)

我会以这种方式在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;

现在你可以这样使用它:

Version : 4.8.0 
Release : 1.cm480.p0.50.el6 
BEGIN yum -y install cloudera-manager-agent 
Setting up Install Process 
Resolving Dependencies 
--> Running transaction check 
---> Package cloudera-manager-agent.x86_64 0:4.8.0-1.cm480.p0.50.el6 will be installed 
--> Processing Dependency: fuse for package: cloudera-manager-agent-4.8.0-1.cm480.p0.50.el6.x86_64 
--> Processing Dependency: fuse-libs for package: cloudera-manager-agent-4.8.0-1.cm480.p0.50.el6.x86_64 
--> Processing Dependency: libxslt for package: cloudera-manager-agent-4.8.0-1.cm480.p0.50.el6.x86_64 
--> Processing Dependency: cyrus-sasl-gssapi for package: cloudera-manager-agent-4.8.0-1.cm480.p0.50.el6.x86_64 
--> Processing Dependency: redhat-lsb for package: cloudera-manager-agent-4.8.0-1.cm480.p0.50.el6.x86_64 
--> Running transaction check 
---> Package cloudera-manager-agent.x86_64 0:4.8.0-1.cm480.p0.50.el6 will be installed 
--> Processing Dependency: redhat-lsb for package: cloudera-manager-agent-4.8.0-1.cm480.p0.50.el6.x86_64 
---> Package cyrus-sasl-gssapi.x86_64 0:2.1.23-15.el6_6.2 will be installed 
---> Package fuse.x86_64 0:2.8.3-4.el6 will be installed 
---> Package fuse-libs.x86_64 0:2.8.3-4.el6 will be installed 
---> Package libxslt.x86_64 0:1.1.26-2.el6_3.1 will be installed 
--> Finished Dependency Resolution 
*******Error: Package: cloudera-manager-agent-4.8.0-1.cm480.p0.50.el6.x86_64 (cloudera-manager) 
Requires: redhat-lsb******* 
You could try using --skip-broken to work around the problem 
You could try running: rpm -Va --nofiles --nodigest 
END (1) 
remote package cloudera-manager-agent could not be installed, giving up 
waiting for rollback request

当然,这取决于你需要如何使用它。如果你有很多属性,你应该只运行一次这个方法让对象不运行多个查询,如果你将它用于大型集合,你还应该重新考虑改进低级数据库查询。

答案 1 :(得分:1)

这并没有按照您的要求完全创建相关对象,但出于输出数据或在没有相关模型的情况下复制Kohana的空输出的目的,我倾向于使用{{为此目的,1}}或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');

中的getRelationshipFromMethod()方法
Illuminate\Database\Eloquent\Model