【发布时间】:2018-05-26 05:17:03
【问题描述】:
我正在尝试加载使用route model binding 通过load() 方法检索的模型的关系,但它似乎不起作用。关于我做错了什么有什么想法吗?
public function update(UpdateOrganisationFormRequest $request, Organisation $organisation)
{
$organisation->load('contacts');
dd(
$organisation->contacts, // returns empty collection
Organisation::first()->contacts // returns values I generated via factory
);
}
这些答案表明这是正确的方法:
Eager loading with route model binding
Laravel Route model binding with relaionship
https://laracasts.com/discuss/channels/laravel/laravel-model-binding-with-eager-loading
这是我的关系定义:
class Organisation extends Model
{
public function contacts()
{
return $this->hasMany(OrganisationContact::class);
}
}
class OrganisationContact extends Model
{
public function organisation()
{
return $this->belongsTo(Organisation::class);
}
}
我考虑过自定义解析逻辑,但似乎有点矫枉过正,因为我只需要为此更新过程加载一些关系。
任何帮助将不胜感激!谢谢。
更新
感谢 cmets,我意识到路由模型绑定没有返回任何内容。对于进一步的上下文...我正在运行一个测试,其中我生成一个 Organisation 模型,然后点击此资源的更新路线,代码如下所示:
测试类:
/** @test */
public function existing_organisation_can_be_updated()
{
// Arrange
$organisation = factory(Organisation::class)->create();
factory(OrganisationContact::class)->create([
'organisation_id' => $organisation->id,
]);
/*
note:
dd( route('admin.organisation.update', $organisation->id) )
produces: "http://mydevurl.dev/admin/organisation/1"
*/
// Act
$response = $this->put(route('admin.organisation.update', $organisation->id), [
'name' => 'New name',
]);
// ... assertions and other stuff
}
资源控制器
public function update(UpdateOrganisationFormRequest $request, Organisation $organisation)
{
// this return null ???
dd(
$organisation->id
);
// update logic ...
}
更新 2 - 架构
_create_organisations_table.php
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateOrganisationsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('organisations', function (Blueprint $table) {
$table->increments('id');
// some other fields
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('organisations');
}
}
_create_organisation_contacts
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateOrganisationContacts extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('organisation_contacts', function (Blueprint $table) {
$table->increments('id');
// some other fields
$table->timestamps();
// the relationship
$table->foreign('organisation_id')->references('id')->on('organisations')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('organisation_contacts');
}
}
【问题讨论】:
-
你确定
$organisationfrom parameter和Organisation::first()是一样的吗? -
请显示您的架构。您可能还想检查该特定组织是否有任何联系人。
-
试试这个
Organisation::find($organisation->id)->contacts看看有没有!! -
啊,这是因为我使用了
WithoutMiddleware特征,它提取了通过中间件管理的绑定 -
你自己搞清楚了;)很好!