【问题标题】:Call to a member function addEagerConstraints() on string - Laravel 8调用字符串上的成员函数 addEagerConstraints() - Laravel 8
【发布时间】:2021-12-10 03:32:28
【问题描述】:

我想通过 type_name 属性获得响应,而不在表中添加新字段

{
  "status": 200,
  "message": "OK",
  "data": {
    "id": 23,
    "uuid": "9b1d33f9-0e44-4161-9936-ec41309697a5",
    "sender_id": null,
    "receiver_id": 2,
    "type": 0,
    "coin": 200,
    "balance": 27000,
    "description": "Topup 200 coin",
    "type_name": "Topup"
}

因此我尝试在 CoinTransaction 模型中创建一个名为 typeName() 的方法,希望可以像这样通过 with() 方法调用该方法:

$transaction = CoinTransaction::create([
     'receiver_id'   => auth()->user()->id,
     'coin'          => $request->coin,
     'balance'       => $predefineCoin->balance ?? 1000,
     'type'          => 0,
     'description'   => $request->description
]);

$transaction = CoinTransaction::with(['typeName'])->find($transaction->id);

但它返回一个错误:

Error: Call to a member function addEagerConstraints() on string...

在我的 CoinTransaction 模型中

class CoinTransaction extends Model
{
    use HasFactory;

    protected $guarded  = ['id'];


    public function sender() {
        return $this->belongsTo(User::class, 'sender_id');
    }


    public function receiver() {
        return $this->belongsTo(User::class, 'receiver_id');
    }


    public function typeName() {
        $typeName = null;

        switch($this->type){
            case 0: $typeName = 'Topup'; break;
            default: $typeName = 'Unknown';
        }

        return $typeName;
    }
}

【问题讨论】:

    标签: php laravel eloquent model laravel-8


    【解决方案1】:

    typeName 不是relationship method 所以你有typeName() 如下所示

    $coin=CoinTransaction::find($transaction->id); 
    dd($coin->typeName());
    

    要将type_name 属性添加到现有响应,您可以使用Mutators

    参考:https://laravel.com/docs/8.x/eloquent-mutators#accessors-and-mutators

    所以在CoinTransaction中添加下面的属性和方法

    protected $appends = ['type_name'];
    

    和方法

    public function getTypeNameAttribute()
    {
        $typeName = null;
    
            switch($this->type){
                case 0: $typeName = 'Topup'; break;
                default: $typeName = 'Unknown';
            }
    
            return $typeName;    
    }
    

    所以在控制器中

    $transaction = CoinTransaction::find($transaction->id);
    

    【讨论】:

    • 感谢先生,效果很好
    猜你喜欢
    • 1970-01-01
    • 2022-01-08
    • 2020-07-26
    • 2021-07-20
    • 2018-12-17
    • 2023-03-14
    • 1970-01-01
    • 2020-03-01
    • 1970-01-01
    相关资源
    最近更新 更多