我有一张桌子,名为汽车,有2个字段id, matriculation
。然后,我有另一个表名为系列,有两个字段id, name
。
我在我的桌车上创造了我的fk_serie
。
public function up()
{
Schema::create('cars', function (Blueprint $table) {
$table->increments('id');
$table->string('matriculation', 25);
$table->integer('fk_serie')->unsigned();
$table->foreign('fk_serie')->references('id_serie')->on('serie');
$table->timestamps();
});
}
这是我关于表系列的信息。
public function up()
{
Schema::create('series', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 30);
$table->timestamps();
});
}
在我的模型中,我只在模型Car上有一个功能。
public function serie(){
return $this->belongsTo('App\Serie', 'fk_serie');
}
我的模特系列中没有任何东西
class Serie extends Model
{
//
}
模型系列是空的是正常的吗?因为,我的加入工作。
你怎么看 ?
有错误吗?
正如Dparoli
在评论中提到的,如果您不需要以下查询,那么您的上述关系结构是正常的
Serie::with('cars')->find($id)
但是如果你想在Serie
模型中设置关系,你可以做如下的事情:
class Serie extends Model
{
public function cars() {
return $this->hasMany('App\Car', 'fk_serie'); // your relationship
}
}
之后你可以这样做:
$series = Serie::with('cars')->find($id); //eager loading cars
$cars = $series->first()->cars;