【问题标题】:Filter collections by checking if filed contain value通过检查字段是否包含值来过滤集合
【发布时间】:2019-09-14 10:58:23
【问题描述】:

我有一个带有 color_id 的集合,并且有一个带有 name 和 colors_id 字段的表。如果它存在于字段中,需要检查或连接值,如果 - true,则返回名称。 所以最终结果应该是存在 color_id 的名称集合。

带有colors_id的表格截图

带有 color_id 的表格截图

【问题讨论】:

  • 用户和颜色表之间的多对多关系不是更好吗?数据透视表不会在列中保留 id 列表,而是匹配用户的 id 和颜色的 id。查询和管理这种结构会容易得多。
  • Dino Numić - 感谢您的建议,将尝试!
  • 草莓 - 深入阅读,我尝试寻求方法,那么示例呢??!!!感谢您的减...

标签: mysql laravel


【解决方案1】:

我会这样做。首先,创建一个枢轴php artisan make:migration create_color_user_table

在迁移的up方法中

 $table->unsignedBigInteger('user_id');
 $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

 $table->unsignedBigInteger('color_id');
 $table->foreign('color_id')->references('id')->on('colors')->onDelete('cascade');

在您的用户模型中

public function colors()
    {
        return $this->belongsToMany(Color::class, 'color_user');
    }

当您有一种颜色或一组颜色要保存给用户时

$user->colors()->sync([1, 2, 3]);

如果你想获取用户颜色

$user->colors;

如果您想要具有特定颜色的用户

$user = User::whereHas('colors', function ($q) use ($color){
    $q->where('id', $color->id);
})->get();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-04
    • 2014-04-06
    • 2021-02-19
    • 2021-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    相关资源
    最近更新 更多