[英]how to get desired column from other table
there are two tables products and categories, that I created by PHPMyAdmin.有两个表产品和类别,我由 PHPMyAdmin 创建。 In the products table, it has a column name prd_category that has the foreign key of table categories named cat_id(primary key of categories table).
在 products 表中,它有一个列名 prd_category ,它具有名为 cat_id 的表类别的外键(类别表的主键)。
i am quite new in laravel i want return all data from product table with category name(cat_name) from another table我在 Laravel 中很新,我想从另一个表中返回产品表中的所有数据,类别名称(cat_name)
//here is my controller //这是我的控制器
use App\Models\product;
class items extends Controller
{
public function sample(){
return product::all();
}
}
//route //路线
Route::get('/',[items::class,'sample']);
//model for products table //产品表的模型
class product extends Model
{
use HasFactory;
function category(){
return $this->hasOne('App\Models\category','cat_id','prd_id');
}
}
//model for category //类别模型
class category extends Model
{
protected $table='categories';
use HasFactory;
}
pls help and thanks in advance..请帮助并提前致谢..
you can use this code:您可以使用此代码:
$products = product::whereHas('category',function($q)use($cat_name){
$q->where('name',$cat_name)
})->get();
or :或者 :
$categories = Category::where('name',$cat_name)->get()->pluck('id')->toArray()
$products = product::whereIn('category_id',$categories)->get();
Are you sure that one-to-many relation is correct?你确定一对多的关系是正确的吗? If a product can belong to many categories, you need to use many-to-many relations.
如果一个产品可以属于多个类别,则需要使用多对多关系。 Furthermore, if something else belongs to categories you should use many-to-many polymorphic relations.
此外,如果其他东西属于类别,您应该使用多对多多态关系。 But let's go with one-to-many.
但是让我们使用一对多。
First, the relation function in Product.php looks incorrect.首先,Product.php 中的关系函数看起来不正确。 I think products should belong to a category.
我认为产品应该属于一个类别。
function category(){
return $this->belongsTo('App\Models\Category','cust_name','name');
}
Then you need to define reverse relation in Category.php然后你需要在 Category.php 中定义反向关系
function products(){
return $this->hasMany('App\Models\Product','cust_name','name');
}
When you define the relations properly, all you need yo do is to fetch data in controller:当您正确定义关系时,您需要做的就是在控制器中获取数据:
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();
in Blade :在刀片中:
{{ $cat->products->cat_name; }}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.