Eloquent 关系和 class 与构造函数

Eloquent relationship and class with constructor

我有两个 类 通过 hasMany 和 belongsTo 方法连接。

class InquiryParameter extends Model
{
    public function translations()
    {
        return $this->hasMany(InquiryParameterTranslation::class);
    }
}

class InquiryParameterTranslation extends Model
{
    public function __construct($inquiry_parameter_id, $language_code, $name, $description)
    {
            $this->inquiry_parameter_id = $inquiry_parameter_id;
            $this->language_code = $language_code;
            $this->name = $name;
            $this->description = $description;
    }
}

但是,当我创建新对象时

$inquiry_parameter = new InquiryParameter;

然后调用方法翻译。

$names = $inquiry_parameter->translations;

我收到错误:

Type error: Too few arguments to function App\InquiryParameterTranslation::__construct(), 0 passed in /Users/SouL-MAC/Code/konfig/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php on line 653 and exactly 4 expected (View: /Users/SouL-MAC/Code/konfig/resources/views/admin/inquiry/parameters.blade.php)

是否可以使用 eloquent 与包含构造函数的 类 的关系?还是我做错了什么?

感谢您的回复

由于您正在扩展一个已有构造函数的给定对象,因此您需要使用相应的属性来调用它。 请参阅 API 以获得 Illuminate\Database\Eloquent\Model

尝试这样的事情:

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

在您的特定情况下,以下方法可行:

public function __construct($inquiry_parameter_id, $language_code, $name, $description)
{
        parent::__construct();

        $this->inquiry_parameter_id = $inquiry_parameter_id;
        $this->language_code = $language_code;
        $this->name = $name;
        $this->description = $description;
}

$names = $inquiry_parameter->翻译;

当上面的代码 运行s 时,它实际上创建了一个 Class InquiryParameterTranslation 的新对象,而不向构造函数传递任何参数。但是您的构造函数需要参数。因此它导致了错误。

此问题的解决方案是更改构造函数代码,如下所示:

public function __construct()
{
    // no parameter in constructor
}

然后创建另一个函数(如下所示)来初始化模型属性

public function initialize($inquiry_parameter_id, $language_code, $name, $description)
{
        $this->inquiry_parameter_id = $inquiry_parameter_id;
        $this->language_code = $language_code;
        $this->name = $name;
        $this->description = $description;
}

通过进行上述更改,您的代码将 运行 正常,当您需要向数据库添加新翻译时,您可以使用以下代码(示例)

$translation = new InquiryParameterTranslation;
$translation->initialize($inquiry_parameter_id, $language_code, $name, $description);

$translation->save();