![](/img/trans.png)
[英]I have 2 MySql tables. How to get not all data from them in 1 sql query?
[英]I have 3 tables with relation. The first table have foreign id of another both tables. I want to know the exact query of fetching the data
1.1) 产品 MODEL -
class Product extends Model
{
protected $table = 'product_table(TableName)';
public function banks()
{
return $this->belongsToMany(Bank::class, 'bank_table', 'bank_id(ForeignKey)', 'id(PrimaryKey)');
}
public function product_category()
{
return $this->belongsToMany(ProductCategory::class, 'productcategory_table', 'productcategory_id(ForeignKey)', 'id(PrimaryKey)');
}
}
1.2) 银行 MODEL -
class Bank extends Model
{
protected $table = 'bank_table(TableName)';
public function product()
{
return $this->hasMany('App\Models\Product', 'id(PrimaryKey)', 'bank_id(ForeignKey)');
}
}
1.3) 产品类别 MODEL -
class ProductCatgory extends Model
{
protected $table = 'mudra5_productcategory';
public function mudra5_product()
{
return $this->hasMany('App\Models\Product');
}
}
public function cat()
{
$alldata = Bank::with(['product'])->first();
dd($alldata->product[0]->product_name);
}
3.路线 -
Route::get('/borrower_profile', 'BorrowerAuth\statementController@cat')->name('mudra5_product');
4.1) 产品表 -
id(int PK) | 产品名称(varchar(100)) | bank_id(外键) | category_id(外键) |
---|---|---|---|
1 | p1 | ||
2 | p2 | ||
4.2) 银行表-
id(int PK) | 银行名称 | 银行标志 |
---|---|---|
1 | 银行1 | 图像1 |
2 | 银行2 | img2 |
4.3) 产品类别表 -
id(int PK) | 分类名称 |
---|---|
1 | 猫1 |
2 | 猫2 |
OUTPUT 应该是 -
ID | 分类名称 | 银行名称 | 产品名称 | |
---|---|---|---|---|
1 | 猫1 | 银行 1 银行 2 银行 3 | p1/p2/p3(bank1), p1/p2(bank2), p1/p2/p3(bank3) | |
2 | 猫2 | 银行 1 银行 2 银行 3 | p1/p2/p3(bank1), p1/p2/p3(bank2), p1/p2/p3(bank3) | |
如果放置外键,则关系为 HasMany-belongsTo (1-N),例如,如果每个产品都有一个类别,那么我们将 category_id 的外键放在产品表中,因为它只能是一个。
在您的情况下,您使用了belongsToMany而不是belongsTo,因此一个产品可以有很多类别,但您还在表中放置了一个外键,它与belongsToMany一起dosnt go。
你不能把 hasMany 和 belongsToMany 放在一起。 选择其中之一。
一个belongsToMany 是一个用于NN 关系的eloquent 关系,它们需要一个pivot 表,没有表可以保存另一个_id,因此您创建一个具有两个id 的picot 表,该表将处理关系查询流量。
如果你想保护你呈现的关系而不是你需要 5 个表(不是 3 个)
产品分类 银行类_产品银行_产品
ID | 产品名称 |
---|---|
1 | p1 |
2 | p2 |
ID | 分类名称 |
---|---|
1 | c1 |
2 | c2 |
ID | 银行名称 |
---|---|
1 | b1 |
2 | b2 |
ID | catrgory_id | product_id |
---|---|---|
1 | 1 | 2 |
2 | 2 | 1 |
ID | 银行ID | product_id |
---|---|---|
1 | 1 | 2 |
2 | 2 | 1 |
我你 go 通过文档你不必指定外键名的表名 laravel 如果你做了命名权就会自己发现它,
第一个产品:
public function cat()
{
$firstBank= Bank::first();
dd($firstBank->products()->first()->product_name);
}
与您的示例相同的 output 吗? :每个类别及其银行及其产品
public function cat()
{
dd(Catgeory::with('banks' , 'products')->get());
}
请查看 eloquent ORM 的官方文档这里它通过示例解释了很多事情
检查此 repo以获取标签和帖子之间的多对多关系的参考
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.