代码之家  ›  专栏  ›  技术社区  ›  James

与构装师的雄辩关系与阶级

  •  0
  • James  · 技术社区  · 6 年前

    我有两个通过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;
    

    我收到错误:

    类型错误:函数的参数太少 /Users/SouL MAC/Code/konfig/vendor/laravel/framework/src/Illuminate/Database/elowent/Concerns/关系.php 在第653行,正好需要4个(视图: /用户/SouL MAC/Code/konfig/resources/views/admin/inquiry/参数.blade.php)

    谢谢你的回复

    2 回复  |  直到 6 年前
        1
  •  0
  •   Muhammad Inaam Munir    6 年前

    $names=$inquiry\u参数->翻译;

    当上面的代码运行时,它实际上创建了一个类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();
    
        2
  •  0
  •   Gordon Freeman    6 年前

    因为您要扩展已经有构造函数的给定对象,所以需要使用相应的属性来调用它。 有关详细信息,请参见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;
    }
    
    推荐文章