为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 Laravel 中获取外键的值

如何在 Laravel 中获取外键的值

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

1 回答

?
凤凰求蛊

TA贡献1825条经验 获得超4个赞

卡车表中制造商的外键不是 manufacturer_id。在这种情况下,您需要在模型中声明它:

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

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


查看完整回答
反对 回复 2023-04-21
  • 1 回答
  • 0 关注
  • 87 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信