【问题标题】:Property [id] does not exist on the Eloquent builder instance in Laravel 8 and Livewire 2.7Laravel 8 和 Livewire 2.7 的 Eloquent 构建器实例上不存在属性 [id]
【发布时间】:2022-01-17 01:33:47
【问题描述】:

当从car 的数据库中选择时,我的users 可以创建多个usercar。我需要获取选定的car 值,但是当我dd 值时,我得到Property [id] does not exist on the Eloquent builder instance. 错误。 wire:model="car_id" 是下面代码中使用的选择输入值。

AddUserCar.php

...
class AddUserCar extends Component
{
    public $showAnotherModel = false;

    // Steps
    public $totalSteps = 8;
    public $step = 1;
    // User
    public $super;
    public $first_name;
    public $last_name;
    public $email;
    public $status = 1;
    public $role = 'Driver';
    // Usercar
    public $car_id;
    public $calc_date;
    public $year;
    public $model;
    // Form Function
    public $car_year;

    //public $cars;
    //public $modelId;

    ...

    public function moveAhead()
    {

        if($this->step == 1) {
            $newCar = Car::where('id', '=', $this->car_id)->get();
            dd($newCar->id); // This is where I get error

            $this->usercarCreated = Usercar::create([
                'year' => $newCar->start_year,
                'model' => $newCar->model,

                'car_id' => $this->car_id,
                'user_id' => Auth::user()->id,
                'tenant_id' => Auth::user()->tenant_id,
                'calc_date' => now()->format('m-d-Y'),
            ]);

            $this->resetErrorBag();
            $this->resetValidation();
        }

        ...

    public function render()
    {
        return view('livewire.add-user-car',
        ['pageTitle' => 'Add Driver Car']);
    }
}

【问题讨论】:

    标签: php laravel laravel-livewire


    【解决方案1】:

    使用->get() 检索表中的所有行:

    $cars = Car::where('id', '=', $this->car_id)->get();
    
    foreach($cars as $car){
        echo $car->id;
    }
    
    // ERROR, because $cars isn't a single row
    dd($cars->id);
    

    使用->first() 从表中检索单行/列。

    $car = Car::where('id', '=', $this->car_id)->first();
    // or 
    $car = Car::find($this->car_id);
    
    // WORK
    dd($car->id);
    

    【讨论】:

    • 选择了$car = Car::find($this->car_id);,因为它更干净。谢谢。
    【解决方案2】:
    $newCar = Car::where('id', '=', $this->car_id)->get();
    

    这条语句没有找到任何数据,所以$newcar为空,空对象没有ID

    【讨论】:

      猜你喜欢
      • 2021-07-25
      • 2021-01-06
      • 1970-01-01
      • 2022-01-15
      • 2020-08-02
      • 1970-01-01
      • 2021-11-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多