我在与Laravel 5的关系方面遇到了麻烦。我有2个模型Crew
和Event
以及相应的表格crews
和events
。船员有很多活动,活动有一个船员。我按如下方式设置模型和迁移:
架构:
//Crews
Schema::connection('scheduling')->create('crews', function ($table) {
$table->increments('id');
$table->text('name');
$table->boolean('solo');
$table->boolean('active');
$table->text('phone');
});
//Events
Schema::connection('scheduling')->create('events', function ($table) {
$table->increments('id');
// ...
$table->integer('crew_id')->unsigned();
$table->foreign('crew_id')->references('id')->on('crews');
$table->text('notes');
// ...
$table->timestamps();
});
型号:
namespace App\Models\Scheduling;
use Illuminate\Database\Eloquent\Model;
class Crew extends Model {
public $connection = "scheduling";
public $table = "crews";
public function events() {
return $this->hasMany('App\Models\Scheduling\Event', 'id', 'crew_id');
}
public static function active() {
return Crew::where('active', 1)->get();
}
}
namespace App\Models\Scheduling;
use Illuminate\Database\Eloquent\Model;
class Event extends Model {
public $connection = "scheduling";
public $table = "events";
public function crew() {
return $this->belongsTo('App\Models\Scheduling\Crew', 'crew_id', 'id');
}
}
如果我运行Crew::find(102)->events;
,我最终会得到一个空集合。
如果我运行Events::where('crew_id', 102)->get();
,我最终得到了我预期的事件列表。
知道我在这里做错了吗?
答案 0 :(得分:1)
您对事件关系的定义无效 - 您以错误的顺序传递参数。
替换:
return $this->hasMany('App\Models\Scheduling\Event', 'id', 'crew_id');
带
return $this->hasMany('App\Models\Scheduling\Event', 'crew_id', 'id');
或只是
return $this->hasMany('App\Models\Scheduling\Event');
因为您使用列名的默认值,所以不需要将它们传递给关系定义。