laravel:无法在控制器中使用模型方法获取属性

时间:2018-10-09 08:01:27

标签: php laravel model eloquent laravel-5.6

我已经尝试了一段时间了。大多数时候,我通过使用访问器来解决它。我目前正在尝试获取该列是否存在,并在我的模型中创建了一个假定返回布尔值的函数。

型号代码:

class Inventory extends Model
{
    protected $attributes = ['inventory'];   
    protected $appends = ['colorThumb'];

    public function hasAttribute($attr){
      return array_key_exists($attr, $this->attributes);
    }
}

控制器代码:

public function allInvOperation(Request $request){
    $inv = Inventory::where('is_deleted', 0)->with(['product', 'size','color'])->orderByDesc('id')->get();       
    if(!is_null($request->searchText)){
        dd($inv->hasAttribute('inventory'));

        $inv = Inventory::where('is_deleted', 0)->with(['product', 'size','color'])->orderByDesc('id');

        if($request->inv_filter == 'inventory'){
            $inv = $inv->where('inventory', 'like', "%".$request->searchText."%")->get();
        }
        if($request->inv_filter == 'code'){
            $inv = $inv->whereHas('product', function ($q) use ($request){
                $q->where('code', "%".$request->searchText."%");
            })->get();
        }
    }

错误

Method Illuminate\Database\Eloquent\Collection::hasAttribute does not exist.

1 个答案:

答案 0 :(得分:2)

您在hasAttribute上执行的代码是Collection个对象,您需要在该查询上使用first以获得单个结果,以后可以在其中进行{{1 }}

相关问题