dssqq82402 2018-09-12 09:07
浏览 56
已采纳

雄辩的关系和类与构造函数

I have two classes which are connected through hasMany and belongsTo method.

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;
    }
}

However, when I create new object

$inquiry_parameter = new InquiryParameter;

And then call method translations.

$names = $inquiry_parameter->translations;

I received error:

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)

Is it possible to use eloquent relationship with classes which contains constructor ? Or am I doing something wrong ?

Thanks for your replies

  • 写回答

2条回答 默认 最新

  • dpde7365 2018-09-12 10:42
    关注

    $names = $inquiry_parameter->translations;

    When above code runs, it actually creates a new object of Class InquiryParameterTranslation without passing any parameters to constructor. But your constructor expects parameters. Therefore it is causing error.

    Solution to this problem is that you change your constructor code as given below:

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

    Then create another function (as given below) to initialize model properties

    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;
    }
    

    By making above changes your code will run fine and when you need to add new translation to database you can use following code (Example)

    $translation = new InquiryParameterTranslation;
    $translation->initialize($inquiry_parameter_id, $language_code, $name, $description);
    
    $translation->save();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助