[英]how to get desired column using foreign key from another table in laravel
[英]how to get desired column from other table
有兩個表產品和類別,我由 PHPMyAdmin 創建。 在 products 表中,它有一個列名 prd_category ,它具有名為 cat_id 的表類別的外鍵(類別表的主鍵)。
我在 Laravel 中很新,我想從另一個表中返回產品表中的所有數據,類別名稱(cat_name)
//這是我的控制器
use App\Models\product;
class items extends Controller
{
public function sample(){
return product::all();
}
}
//路線
Route::get('/',[items::class,'sample']);
//產品表的模型
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();
你確定一對多的關系是正確的嗎? 如果一個產品可以屬於多個類別,則需要使用多對多關系。 此外,如果其他東西屬於類別,您應該使用多對多多態關系。 但是讓我們使用一對多。
首先,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();
在刀片中:
{{ $cat->products->cat_name; }}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.