我對 Laravel 模型關系有疑問。我需要讓用戶創(chuàng)建新卡車。但是,我需要將制造商的字段存儲為 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此視圖現(xiàn)在顯示 id。我需要做什么來顯示制造商標題(manufacturers.manufacturer)而不是 id?謝謝大家!
如何在 Laravel 中獲取外鍵的值
慕尼黑8549860
2023-04-21 16:39:05