Background

Given we have the following two tables where type_id references a row in questionType:

question

id | type_id | description
---+---------+------------
1  | 1       | A nice question
.. | ..      | ..

questionType

id | name 
---+----------------
1  | Multiple-choice 
.. | ..

有以下Eloquent 的模型:

class Question extends Model {
    public function type() {
        return $this->hasOne( 'QuestionType', 'id', 'type_id' );
    }
}

class QuestionType extends Model {
}

Question 1

How can I add a new question that references an existing question type without manually doing anything with ids? For example the following works but is ugly imo since I have to manually assign the corresponding question type id:

$q = new Question;
$q->type_id = 1; // Multiple-choice
$q->description = 'This is a multiple-choice question';
$q->save();

有人会认为有一种方法可以让ORM处理id分配(在ORM中避免这样的事情难道不是重点吗?),类似于(this does not work in Eloquent ORM)的东西:

$q = new Question;
$q->type = QuestionType.where('name', '=', 'Multiple-choice');
$q->description = 'This is a multiple-choice question';
$q->save();

Question 2

In relation to question 1, how would I go about adding a new question that references a new question type without manually doing anything with ids? Similarly I imagine something along the lines of:

$t = new QuestionType;
$t->name = 'Another type';

$q = new Question;
$q->type = $t;
$q->description = 'This is a multiple-choice question';
$q->save();

Here I'd like $q->save() to save both the new question type and question (or something similar).

以下是有效的,但我还是要自己分配id,我认为ORM应该处理这个id:

$t = new QuestionType;
$t->name = 'Another type';
$t->save();

$q = new Question;
$q->type = $t->id;
$q->description = 'This is a multiple-choice question';
$q->save();

I've tried playing with different combinations of save(), update() methods without luck. I also looked for attach() which exists on the hasMany relationships but seem to be missing in hasOne.

推荐答案

First off, you misunderstood the relation you refer to.

Here's what you need:

// Question model
public function questionType()
{
  return $this->belongsTo('QuestionType', 'type_id');
}

// QuestionType model
public function questions()
{
  return $this->hasMany('Question', 'type_id');
}

然后你可以这样把它们连接起来:

$questionType = QuestionType::where(..)->first();

$question = new Question;
... // do something with it

// associate
$question->questionType()->associate($questionType);

// or the other way around - save new question and link to the type:
$questionType->questions()->save($question);

You can explicitly pass an id to associate as well:

$question->type_id = $someTypeId;
$question->save();

你不能这么做:

$question->questionType = $someQuestionType;

for this way Eloquent handles model attributes, not relations.


Question 2:

$questionType = new QuestionType(['name' => 'multiple']);
$questionType->save();

$question = new Question([ ... some values ... ]);

// then either this way:
$questionType->questions()->save($question);

// or, again, the other way around:
$question->questionType()->associate($questionType);
$question->save();

Laravel相关问答推荐

Vue 组件中的图像不适用于 Vite + Laravel

Laravel REST API:如何将数据库列名与参数的另一个名称映射?

assertSee 由于 html 代码中的空格而失败

Laravel phpunit 测试失败并出现 PDOException:SQLSTATE[HY000]:一般错误:1 接近0:语法错误

在 Laravel 中清除 Routes&config:cache 后未定义的常量

1 子编译中的警告(使用'stats.children:true'和'--stats-children'了解更多详细信息)

laravel render() 方法有什么用?

Laravel - 将变量从中间件传递到控制器/路由

使用 Amazon S3 的 Storage::get() 返回 false

Laravel 中的 index()" 是什么意思?

413请求实体在laravel homestead for windows中太大的nginx服务器

Web 服务器如何处理请求?

在 Laravel 中,如何获取 *only* POST 参数?

Laravel:验证 json 对象

如何在 Laravel 4 中组织不同版本的 REST API 控制器?

在 Laravel artisan 命令中使用详细

在我的编辑器中管理上传文件的最佳方式?

如何在 Eloquent Orm 中实现自引用(parent_id)模型

Laravel 4:分析器在哪里?

函数参数前的三个点代表什么?