第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 Laravel 中獲取外鍵的值

如何在 Laravel 中獲取外鍵的值

PHP
慕尼黑8549860 2023-04-21 16:39:05
我對 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?謝謝大家!
查看完整描述

1 回答

?
鳳凰求蠱

TA貢獻1825條經(jīng)驗 獲得超4個贊

卡車表中制造商的外鍵不是 manufacturer_id。在這種情況下,您需要在模型中聲明它:

return $this->belongsTo(Manufacturer::class, 'make_id' )

 return $this->hasMany(Truck::class, 'make_id' )


查看完整回答
反對 回復 2023-04-21
  • 1 回答
  • 0 關注
  • 146 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號