//controller
$promotion = Promotion::findOrFail($id);
//return
Array
(
[id] => 2
[en_title] => promo1
[game_id] => Array
(
[0] => 3
[1] => 4
[2] => 5
)
[amount] => 100.00
[start_at] => 2021-02-22
[end_at] => 2222-02-22
[status] => 1
)
//model promotion
class Promotion extends Model
{
use HasFactory;
protected $guarded = [];
protected $casts = [
'game_id' => 'array'
];
public function getAllGames()
{
return $this->belongsTo(Game::class, 'game_id', 'id');
}
}
问题:
目前,我有 2 个表,分别是 games 和 promotion,但是在建立关系时我遇到了麻烦,因为 game_id 列promotion 表内是一个 JSON,因此很难连接它。是否有任何解决方法可以轻松地将它们连接在一起以检索游戏数据?
最佳答案
在您的游戏和促销表之间建立多对多关系,
将您的 game_ids 放入数据透视表 (game_promotion) 而不是 JSON 字段中,
Many To Many Relationships
关于mysql - laravel 与 json 列的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69778587/