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 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程