项目表
| id | item_id | item_title | |-------|---------|------------| | 1 | 1002 | A | | 2 | 1003 | B | | 3 | 1004 | C |
销售表
| id | item_id | |----|-----------| | 1 | 1002 1003 | | 2 | 1003 1004 | | 3 | 1004 1002 |
我想要结果:销售表 1。商品标题是 A B
我想将 sells 表与 item 表合并,然后将 sells 表的 item_id 与 item 表的 item_title 相匹配。
最佳答案
表定义看起来不正确,您应该有一个将 items
与 sells
链接起来的数据透视表,因此有一个 sell_item
表:
item_id | sell_id
-----------------
1 | 1
1 | 3
2 | 1
2 | 2
3 | 2
3 | 3
然后使用 eloquent 创建模型来表示表并使用 BelongsToMany
定义关系:
class Item extends Model {
public function sells() {
return $this->belongsToMany(Sell::class);
}
}
class Sell extends Model {
public function items() {
return $this->belongsToMany(Item::class);
}
}
任一模型的每个实例都可以通过 $item->sells
和 $sell->items
访问其相关模型。
如果不走 Eloquent 路线,查询构建器可以执行联接:
DB::table('sells')->join('items', 'sells.item_id', '=', 'items.item_id')
->select('sells.*', 'items.title')
->get();
关于mysql - Laravel5 : Eloquent and JOIN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49713798/