繁体   English   中英

属于Laravel

[英]BelongsTo in Laravel

我有一个表,它被命名为cars,具有2个字段id, matriculation 然后,我有另一个表,该表名为series,具有2个字段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
{
    //
}

Serie模型为空是否正常? 因为,我的加入有效。

你怎么看 ?

概观

有错误吗?

正如Dparoli在评论中提到的,如果您不需要以下查询,则您的上述关系结构正常

Serie::with('cars')->find($id)

但是,如果要在Serie Model中设置关系,可以执行以下操作:

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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM