如何制作一对多访问器?
用户模型:
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');
});
}
Controller:
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
希望这会有所帮助。