如何在 Laravel 中获取外键的值

我对 Laravel 模型关系有疑问。我需要让用户创建新卡车。但是,我需要将制造商的字段存储为 ID,而不是标题。所以我决定制作两个具有一对多关系的表(制造商和卡车)(制造商有多辆卡车,而一辆卡车有一个制造商)。


这是迁移文件。制造商表:


public function up()

{

    Schema::create('manufacturers', function (Blueprint $table) {

        $table->bigIncrements('id');

        $table->string('manufacturer');

        $table->timestamps();

    });

}

卡车表:


public function up()

{

    Schema::create('trucks', function (Blueprint $table) {

        $table->bigIncrements('id');

        $table->unsignedBigInteger('make_id');

        $table->unsignedInteger('year');

        $table->string('owner');

        $table->unsignedInteger('owner_number')->nullable();

        $table->text('comments')->nullable();

        $table->foreign('make_id')->references('id')->on('manufacturers');


        $table->timestamps();

    });

}

Manufacturer.php模型:


namespace App;


use Illuminate\Database\Eloquent\Model;


class Manufacturer extends Model

{

/**

 * @var string

 */

protected $table = 'manufacturers';


/**

 * @var array

 */

protected $fillable = [

    'manufacturer', 

];


public function trucks(){

    return $this->hasMany(Truck::class);

}

}

Truck.php 模型:


namespace App;


use Illuminate\Database\Eloquent\Model;


 class Truck extends Model

 {

 /**

 * @var string

 */

protected $table = 'trucks';


/**

 * @var array

 */

protected $fillable = [

    'make_id', 'year', 'owner', 'owner_number', 'comments',

];


public function manufacturer(){

    return $this->belongsTo(Manufacturer::class);

}

}

控制器文件:


public function index()

{

    $trucks = Truck::all();

    return view('trucks.index')->with('trucks', $trucks);

}

索引.blade.php


@foreach($trucks as $truck)

            <tbody>

            <tr>

                <td>{{$truck->make_id}}</td> //I need this one to show manufacturers title

                <td>{{$truck->year}}</td>

                <td>{{$truck->owner}}</td>

                <td>{{$truck->owner_number}}</td>

                <td>{{$truck->comments}}</td>

            </tr>

            </tbody>

            @endforeach

此视图现在显示 id。我需要做什么来显示制造商标题(manufacturers.manufacturer)而不是 id?谢谢大家!


慕尼黑8549860
浏览 116回答 1
1回答

凤凰求蛊

卡车表中制造商的外键不是 manufacturer_id。在这种情况下,您需要在模型中声明它:return&nbsp;$this->belongsTo(Manufacturer::class,&nbsp;'make_id'&nbsp;)和&nbsp;return&nbsp;$this->hasMany(Truck::class,&nbsp;'make_id'&nbsp;)
打开App,查看更多内容
随时随地看视频慕课网APP