显示基于另一个 table 上的外国 ID 的列数据

Display column data based from foreign id on another table

我想显示 kategori_name from kategori table 基于 id_kategori 从 produks tabel 到我的视图,但使用 Eloquent 或 Query Builder

这是我的产品迁移

Schema::create('produks', function (Blueprint $table) {
    $table->id();
    $table->string('product_name');
    $table->foreignId('id_kategori')->references('id')->on('kategoris');
    $table->timestamps();
}); 

这是类别迁移

Schema::create('kategoris', function (Blueprint $table) {
    $table->id();
    $table->string('kategori_name');
    $table->timestamps();
});

这是我的尝试:

$joinkategori = DB::table('produks')->where('id_kategori')->where(Kategori::select('kategori_name')->first());
return view('admin/createproduk', compact('joinkategori'));

但仍然出现这样的错误

Undefined property: Illuminate\Database\MySqlConnection::$nama_kategori (View: D:\oricraft\resources\views\admin\createproduk.blade.php)

如何使用 eloquent 或查询生成器实现此目的?谢谢

首先创建两个模型

Product 对于 produks

Kategori for kategoris(根据已经创建的问题)

所以在产品模型中添加关系

public function category(){

  return $this->belongTo(Kategori::class,'id_kategori','id')
}

然后n查询

$joinkategori =Product::with('category')->get()

$joinkategori =Product::with('category')->has('category')->get()