2
//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 个表,分别是gamesPromotion,但是在建立关系时遇到了麻烦,因为 Promotion 表中的 game_id 列JSON ,所以很难加入它。是否有任何解决方法可以轻松地将它们连接在一起以检索游戏数据?

4

1 回答 1

2

在您的游戏和促销表之间建立多对多关系,
将您的 game_ids 放在数据透视表(game_promotion)而不是 JSON 字段中,
多对多关系

于 2021-10-30T10:19:40.813 回答