最近中文字幕高清中文字幕无,亚洲欧美高清一区二区三区,一本色道无码道dvd在线观看 ,一个人看的www免费高清中文字幕

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

如何在 Laravel 中獲取外鍵的值

如何在 Laravel 中獲取外鍵的值

PHP
慕尼黑8549860 2023-04-21 16:39:05
我對(duì) Laravel 模型關(guān)系有疑問(wèn)。我需要讓用戶(hù)創(chuàng)建新卡車(chē)。但是,我需要將制造商的字段存儲(chǔ)為 ID,而不是標(biāo)題。所以我決定制作兩個(gè)具有一對(duì)多關(guān)系的表(制造商和卡車(chē))(制造商有多輛卡車(chē),而一輛卡車(chē)有一個(gè)制造商)。這是遷移文件。制造商表:public function up(){    Schema::create('manufacturers', function (Blueprint $table) {        $table->bigIncrements('id');        $table->string('manufacturer');        $table->timestamps();    });}卡車(chē)表: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。我需要做什么來(lái)顯示制造商標(biāo)題(manufacturers.manufacturer)而不是 id?謝謝大家!
查看完整描述

1 回答

?
鳳凰求蠱

TA貢獻(xiàn)1825條經(jīng)驗(yàn) 獲得超4個(gè)贊

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

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

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


查看完整回答
反對(duì) 回復(fù) 2023-04-21
  • 1 回答
  • 0 關(guān)注
  • 169 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢(xún)優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)