【问题标题】:Create construct function for Eloquent Model Laravel为 Eloquent 模型 Laravel 创建构造函数
【发布时间】:2020-02-11 21:25:40
【问题描述】:

我有这个代码

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=new CRUD('HW101950054393'); 因为当我尝试在构造函数中回显 $collection 变量时,我注意到了这个错误

数组到字符串的转换

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

【问题讨论】:

  • 这能回答你的问题吗? A __construct on an Eloquent Laravel Model
  • 不,这不是我的答案
  • CRUD 类文件中有命名空间吗?
  • 我试过你的代码,它应该可以工作。
  • 是的,我有,命名空间 App;

标签: laravel eloquent


【解决方案1】:

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

我正在使用 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');
}

工作正常。

【讨论】:

  • @M.Bwe 我添加了我如何调用测试类。我只是添加了一条路线并通过浏览器调用它mydomain.dev/test
  • 好的,谢谢你,仍然不适合我,谢谢你的帮助
  • 当我使用此代码来调用构造函数时,我什么都没有得到 $device_mode=new CRUD('HW101950054393');因为当我尝试在构造函数中回显 $collection 变量时,我注意到此错误 > 数组到字符串的转换我不明白,因为我将变量作为字符串传递,但模型将其作为数组处理。为什么会这样,我该如何解决它
  • @M.Bwe 不确定,Jenssegers\Mongodb\Eloquent\Model 中可能使用了集合名称。您可以尝试将您的属性 collection 重命名为 test 或其他内容
  • @M.Bwe,您不能回显数组,请使用var_dumpdd(立即停止执行)安全地查看其内容。
猜你喜欢
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-25
  • 1970-01-01
  • 2021-11-02
相关资源
最近更新 更多