【发布时间】:2016-07-09 12:08:42
【问题描述】:
我已经搜索了很多以找到更好的方法。我已经在Laravel docs 上读到了
Eloquent 会尝试将子模型中的父 id 匹配到一个 id 在父模型上。
我有 Idea 和 Document 表。他们有1:M的关系。一个Idea 可以有多个文档,而一个文档只能与一个Idea 相关。
我无法获取要存储的父表 ID。
控制器功能:
public function storeDocuments(DocumentRequest $request) {
if($request->hasFile('doc_name')) {
$filename = $request->file('doc_name')->getClientOriginalName();
$moveFile = $request->file('doc_name')->move('documents/', $filename);
}
$doc = new Document();
$doc->doc_name = $moveFile;
$doc->save();
}
文档模型:
public function idea() {
return $this->belongsTo('App\Idea');
}
创意模型:
public function documents() {
return $this->hasMany('App\Document');
}
请说明将父表的id存入子表的过程,谢谢!
编辑:
public function storeDocuments(DocumentRequest $request) {
if($request->hasFile('doc_name')) {
$filename = $request->file('doc_name')->getClientOriginalName();
$moveFile = $request->file('doc_name')->move('documents/', $filename);
}
$doc = new Document();
$doc->doc_name = $moveFile;
$idea = Idea::find(1); //how to get idea_id here???????
$idea->documents()->save($doc);
return back();
}
我对这种关系很困惑。现在工作了一段时间,想不通。
想法架构:
public function up()
{
//
Schema::create('ideas', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('idea_title');
$table->string('idea_info', 150);
$table->string('idea_image');
$table->string('selection');
$table->longText('idea_description');
$table->string('idea_location');
$table->integer('idea_goal')->unsigned();
$table->integer('pledge_amount')->unsigned();
$table->string('set_equity')->nullable();
$table->boolean('status')->default(0);
$table->rememberToken();
$table->timestamps();
$table->softDeletes();
});
}
文档架构:
public function up()
{
//
Schema::create('documents', function (Blueprint $table) {
$table->increments('id');
$table->integer('idea_id')->unsigned();
$table->string('doc_name');
$table->rememberToken();
$table->timestamps();
$table->softDeletes();
});
}
【问题讨论】:
-
由于每个
Document都必须与Idea相关,因此您的控制器函数 中必须有一个Ideaid 或模型可用。要么您需要在表单中选择一个想法,要么您有嵌套资源。 -
如果我理解正确的话。您想用正确的文档保存想法。但是您想检索最后一个 ID 以添加特定想法的文档?我是对的吗?