Laravel雄辩地为模型关系设置默认值吗? [英] Laravel Eloquent setting a default value for a model relation?
问题描述
我有两个模型:
class Product extends Eloquent {
...
public function defaultPhoto()
{
return $this->belongsTo('Photo');
}
public function photos()
{
return $this->hasMany('Photo');
}
}
class Photo extends Eloquent {
...
public function getThumbAttribute() {
return 'products/' . $this->uri . '/thumb.jpg';
}
public function getFullAttribute() {
return 'products/' . $this->uri . '/full.jpg';
}
...
}
这很好用,我可以调用$product->defaultPhoto->thumb
和$product->defaultPhoto->full
并获取相关图像的路径,并使用$product->photos
并遍历所有值来获取所有照片.
This works fine, I can call $product->defaultPhoto->thumb
and $product->defaultPhoto->full
and get the path to the related image, and get all photos using $product->photos
and looping through the values.
当产品没有照片时就会出现问题,我似乎无法找出一种为这种情况设置默认值的方法.
The problem arises when the product does not have a photo, I can't seem to figure out a way to set a default value for such a scenario.
我尝试做类似的事情
public function photos()
{
$photos = $this->hasMany('Photo');
if ($photos->count() === 0) {
$p = new Photo;
$p->url = 'default';
$photos->add($p);
}
return $photos;
}
我还创建了一个全新的Collection
来存储新的Photo
模型,但是它们都返回相同的错误:
I have also creating a completely new Collection
to store the new Photo
model in, but they both return the same error:
Call to undefined method Illuminate\Database\Eloquent\Collection::getResults()
有人做过类似的事情吗?
Has anyone done anything similar to this?
提前谢谢!
推荐答案
您可以在对您进行检查的Product模型上创建访问器.如果您只是想将其定义为方法,则其工作原理也相同(也适用于希望抽象化一些Eloquent调用,为产品使用接口,以防以后更改的情况,等等)
You could create an accessor on the Product model that did the check for you. Works the same if you just wanted to define it as a method, also (good for if you want to abstract some of the Eloquent calls, use an interface for your Product in case you change it later, etc.)
/**
* Create a custom thumbnail "column" accessor to retrieve this product's
* photo, or a default if it does not have one.
*
* @return string
*/
public function getThumbnailAttribute()
{
$default = $this->defaultPhoto;
return ( ! is_null($default))
? $default->thumb
: '/products/default/thumb.jpg';
}
您可能还想研究演示者.在某些情况下有点过大,但是使用起来非常方便(并且将这样的事情从模型中抽象出来).
You might also want to look into Presenters. A bit overkill for some situations, but incredibly handy to have (and abstract things like this away from your models).
这篇关于Laravel雄辩地为模型关系设置默认值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!