如何从其他 table 获取所需的列

how to get desired column from other table

有两个 tables 产品和类别,是我通过 PHPMyAdmin 创建的。 在产品 table 中,它有一个列名 prd_category,它有 table 个类别的外键,名为 cat_id(类别 table 的主键)。

我对laravel很陌生 我想要 return 来自产品 table 的所有数据以及来自另一个 table

的类别名称(cat_name)

//这是我的控制器

use App\Models\product;

class items extends Controller
{
    public function sample(){ 
        return product::all();
    }
}

//路线

Route::get('/',[items::class,'sample']);

//产品型号table

class product extends Model
{
    use HasFactory;

    function category(){
        return $this->hasOne('App\Models\category','cat_id','prd_id');
        
    }
}

//类别模型

class category extends Model
{
    protected $table='categories';
    use HasFactory;

}

请帮助并提前致谢..

您可以使用此代码:

$products = product::whereHas('category',function($q)use($cat_name){
    $q->where('name',$cat_name)
})->get();

或:

$categories = Category::where('name',$cat_name)->get()->pluck('id')->toArray()

$products = product::whereIn('category_id',$categories)->get();

您确定 one-to-many 关系正确吗?如果一个产品可以属于多个类别,则需要使用many-to-many关系。此外,如果其他东西属于类别,您应该使用 many-to-many 多态关系。但是让我们选择 one-to-many.

首先,Product.php 中的关系函数看起来不正确。我认为产品应该属于一个类别。

function category(){
   return $this->belongsTo('App\Models\Category','cust_name','name');     
}

那么你需要在Category.php

中定义反向关系
function products(){
   return $this->hasMany('App\Models\Product','cust_name','name');     
}

正确定义关系后,您需要做的就是在控制器中获取数据:

use App\Models\Category
...
Category::with('products')->get();
you can use relationship with forign key like pro_id

function category(){
   return $this->belongsTo('App\Models\Category','pro_id');     
}

function products(){
   return $this->hasMany('App\Models\Product','id');     
}

$cat = Category::with('products')->all();

在Blade中:

{{ $cat->products->cat_name; }}