【问题标题】:Is it possible to save one to many relation in one line Laravel eloquent是否可以在一行中保存一对多关系 Laravel eloquent
【发布时间】:2018-01-22 00:13:41
【问题描述】:

如何使用 Laravel Eloquent 将这个问题答案关系模型保存在一行中。如果这不可能,那么如何有效地保存这种关系(使用更少的代码行,纯粹使用 Eloquent ORM。)

这是问题模型

class Question extends Model
{
    protected $fillable = ['name' ,'type'];

    public $timestamps = true;

    public function answers(){

        return $this->hasMany('App\Answer');
    }
}

这是答案模型

class Answer extends Model
{
    protected $fillable = ['answer'];

    public $timestamps = true;


    public function question(){

        return $this->belongsTo('App\Question');
    }
}  

【问题讨论】:

  • 我不明白问题是什么,顺便说一句,函数答案应该重命名为复数答案。
  • 感谢答案重命名为答案。
  • @RehmanAkbar 你能更具体地说明你需要什么
  • 保存此答案问题关系的最佳做法是什么。

标签: php database laravel laravel-5 laravel-eloquent


【解决方案1】:

在添加答案之前,您需要先提出一个问题。

<?php

// Create both question and answer in one go.
Question::create(['name' => 'Who is my father?'])
    ->answers()
    ->create(['answer' => 'Darth Vader']);

// If you already have a question and want to add a new answer.
$lukesQuestion->answers()->create(['answer' => 'Darth Vader']);

请参阅Eloquent relations 上的文档。

【讨论】:

    【解决方案2】:

    这就是 Eloquent ORM 的工作方式。如果您想利用 Eloquent,就无法避免这些关系函数。

    如果你愿意,你不必定义这些方法,但是你不能使用 Eloquent 的关系功能。

    最后,这些语句所需的代码大小与语言有关,与框架无关。

    【讨论】:

      猜你喜欢
      • 2013-02-09
      • 1970-01-01
      • 2017-04-20
      • 2021-04-21
      • 2017-07-17
      • 2015-04-12
      • 2015-03-05
      • 1970-01-01
      • 2017-02-22
      相关资源
      最近更新 更多