web-dev-qa-db-ja.com

Laravel Eloquentモデルにカスタム関数を追加するには?

製品モデルがあります

_class Product extends Model
{
    ...

    public function prices()
    {
        return $this->hasMany('App\Price');
    }

    ...
}
_

最低価格を返す関数を追加したいのですが、コントローラでは次を使用して値を取得できます。

_Product::find(1)->lowest;
_

これを製品モデルに追加しました:

_public function lowest()
{
    return $this->prices->min('price');
}
_

しかし、私は言ってエラーが発生しました:

_Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation
_

そして、Product::find(1)->lowest();を使用すると動作します。 Product::find(1)->lowest;を機能させることは可能ですか?

任意の助けをいただければ幸いです。

16
Harrison

モデル内の関数に変数としてアクセスしようとすると、laravelは関連するモデルを取得しようとしているとみなします。それらは動的プロパティと呼ばれます。代わりにカスタム属性が必要です。

モデルに次のメソッドを追加します。

public function getLowestAttribute()
{
    //do whatever you want to do
    return 'lowest price';
}

これで、次のようにアクセスできるはずです。

Product::find(1)->lowest;
31
Rahul M

Eloquentを使用 accessors

public function getLowestAttribute()
{
    return $this->prices->min('price');
}

それから

$product->lowest;
13
huuuk

上記の方法を使用するか、次の方法を使用して既存のモデルに直接関数を追加できます。

class Company extends Model
{
    protected $table = 'companies';

    // get detail by id
    static function detail($id)
    {
        return self::find($id)->toArray();
    }

    // get list by condition
    static function list($name = '')
    {
        if ( !empty($name) ) return self::where('name', 'LIKE', $name)->get()->toArray();
        else return self::all()->toArray();
    }
}

または、Illuminate\Support\Facades\DBを使用します。関数内。これが他の人を助けることを願っています。

3
May Weather VN

なぜあなたはこれをしないのですか?私が知っている、それはあなたが特に求めたものではなく、時には悪い習慣かもしれません。しかし、あなたの場合、私はそれが良いと思います。

$product = Product::with(['prices' => function ($query) {
   $query->min('price');
}])->find($id);
2
Achraf Khouadja