php - Laravel Eloquent:一对多访问器
问题描述
如何制作一对多访问器?
用户模型:
public function histories()
{
return $this->hasMany('App\History');
}
历史模型:
public function user()
{
return $this->belongsTo('App\User');
}
如果我喜欢下面,它将起作用。
用户模型:
public function getHappyHistoryAttribute()
{
return $this->products()->happyHistory()->first()->text;
}
历史模型:
public function scopeHappyHistory(Builder $builder)
{
return $builder->where(function (Builder $query) {
return $query->where('status', 'happy');
});
}
控制器 :
public function show($id)
{
return view("my_view", [
'user' => User::find($id)
]);
}
刀片视图:
{{ dd($user->happy_history) }}
有用 !
但是,如果我想要这个,我该怎么办:
{{ dd($user->histories->happy) }}
我试着喜欢
历史模型:
public function scopeHappyHistory(Builder $builder)
{
return $builder->where(function (Builder $query) {
return $query->where('status', 'happy');
});
}
public function getHappyAttribute()
{
return $this->happyHistory->first()->text;
}
它不起作用!
如果我像这样编码
{{ dd($user->histories->happy) }}
它会回来
此集合实例上不存在属性 [happy]。
如果我像这样编码
{{ dd($user->histories()->happy) }}
它会回来
未定义属性:Illuminate\Database\Eloquent\Relations\HasMany::$happy
纠正我如果我错了
解决方案
它不会那样工作,因为关系是oneToMany
。
尝试在您的用户模型中关注
/**
* @return mixed
*/
public function happyHistory()
{
//Happy history is your scope form History model
//Following will not get you first model
return $this->histories()->happyHistory()->first();
}
这将为您提供第一个模型,然后您可以从用户模型中执行以下操作
$user->happyHistory->text
未经测试,但这应该可以。
此外,您不需要在范围内传递查询生成器。您可以执行以下操作
public function scopeStatus($query, $status = "happy")
{
return $query->where('status', $status);
}
现在您可以将它用于所有status
类型。
History::status()->all(); //Will return all Happy history
History::status("sad")->all(); //Will return all Sad history
希望这可以帮助。
推荐阅读
- ruby-on-rails - Heroku:通过 rake 任务解压 Gzip 文件失败
- swift - Codable 类中的可编码变量
- java - javax.xml.transform.Transformer 未将数据写入 Linux 中的文件
- react-native - JSON 解析错误:无法识别的令牌'<' - react-native
- php - 从 mysqli_multi_query 获取最后一个结果
- twitter-bootstrap - 更新 bootstrap-vue 警报的内容
- javascript - JavaScript,无法对对象进行排序
- html - 使用 CSS 在子菜单下拉菜单下创建子菜单
- java - 如何将图像压缩到 5kb?
- c++ - 与储备无关的向量重新分配