mysql - laravel 与 json 列的关系

标签 mysql laravel eloquent laravel-relations

//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,但是在建立关系时我遇到了麻烦,因为 game_idpromotion 表内是一个 JSON,因此很难连接它。是否有任何解决方法可以轻松地将它们连接在一起以检索游戏数据?

最佳答案

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

关于mysql - laravel 与 json 列的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69778587/

相关文章:

php - 如何在 Laravel 5.6 中修复图像输入值 "null"?

Laravel 与多个自定义数据透视表的多对多关系?

MySQL : How to identify users I follow or follow me from other person's followers?

php - 如何使用 Laravel 和 Eloquent 查询具有多种关系的数据透视表

php - 使用 PHP 面向对象编程简单更新 MySQL

mysql - 给定NOW(),如何在MySQL中获取一周第一天的DATETIME对象?

php - 安全地向 Flash 游戏的获胜者提供唯一的密码?

php - 通过优先级在单个 Laravel 查询中进行多选择查询

php - Laravel 从哪里得到 references() 方法?

php - laravel undefined variable : user