首页 > 解决方案 > 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

纠正我如果我错了

标签: phplaraveleloquentaccessor

解决方案


它不会那样工作,因为关系是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

希望这可以帮助。


推荐阅读