为雄辩的模型Laravel创建构造函数

时间:2020-02-11 11:35:38

标签: laravel eloquent

我有此代码

use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
use Stevebauman\Location\Drivers\Driver;
use Stevebauman\Location\Exceptions\DriverDoesNotExistException;

Class CRUD extends Eloquent {
protected $collection;
   public function __construct($collection ,array $attributes = array())
   {

  parent::__construct($attributes);

       $this->collection = $collection;

   }

}

当我使用此代码来调用构造函数时,我一无所获 $ device_mode =新的CRUD('HW101950054393'); 因为正如我注意到的那样,当我尝试在构造函数中回显$ collection变量时,出现此错误

数组到字符串的转换

我不明白,因为我将变量作为字符串传递,但模型将其作为数组使用。 为什么会发生这种情况,我该如何解决

1 个答案:

答案 0 :(得分:0)

您的代码应该可以使用。仔细检查您的代码是否与您发布的代码相同。

我正在使用Laravel 5.6,并且可以正常工作:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Test extends Model
{
    protected $collection;

    public function __construct($collection, array $attributes = array())
    {
        parent::__construct($attributes);

        $this->collection = $collection;
    }
}

呼叫

Route::get('/test', function () {
    $test = new \App\Test('1234');
}

工作正常。