les*_*gar 5 php laravel eloquent laravel-5
我知道Laravel的访问器和变换器可以在获取或设置模型时调整属性值.但是,这只能使用现有的模型属性来完成.我想知道是否有任何方法可以创建一个accessor和mutator的组合,让我为每个模型项设置自定义属性.
然后,当我用Eloquent检索标签时:
$tags = Tag::all();
Run Code Online (Sandbox Code Playgroud)
我可以在循环中访问现有属性:
foreach ($tags as $tag) {
echo $tag->id.'<br>';
echo $tag->name.'<br>';
// and ohers
}
Run Code Online (Sandbox Code Playgroud)
但也自定义那些我设置一样$tag->customAttr1
,$tag->customAttr2
.
可能吗?
这是向模型添加自定义属性的示例。$appends 数组将添加这些。在使用 eloquent 查询表时,.. 将调用相应的 getter 来设置值。
在以下代码片段中,“ parent_name ”和“ parent_img_url ”是自定义属性,而getParentNameAttribute和getParentImgUrlAttribute是 getter。
可以根据我们的需要修改 getter 的代码。
class Code extends Eloquent {
protected $table = 'codes';
protected $appends = array('parent_name', 'parent_img_url');
protected $guarded = array();
public static $rules = array();
public function components()
{
return $this->belongsToMany('Component', 'component_codes', 'component_id', 'code_id');
}
public function getParentNameAttribute()
{
$parent = Component::find(50);
return $parent->name_en;
}
public function getParentImgUrlAttribute()
{
$parent = Component::find(50);
return $parent->thumb;
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
863 次 |
最近记录: |