mysql - 检索满足第一个表条件的所有值

标签 mysql laravel

enter image description here

我有两个表用户和位置。我需要加入两个表

enter image description here

我需要的是获取用户表中存在的所有用户的所有区域号码。 即用户 1 在第二个表中有 3 个条目,所以我需要以这样的方式连接该表,即 id1 = 1 面积 = 2,3

区域 2 是重复的,因此不要包含两次

我尝试了加入,但现在找到了正确的方法。

我尝试了什么?

    $location = User::
  join('addresses','users.id1','=','addresses.id1')                                    ->select('users.id1','addresses.area')
                    ->get();

预期输出

用户1 -> 区域 ->2,3

最佳答案

这里有两种方法可以做到这一点。

首先你可以使用 Laravel 关系:-

在您的模型User中创建关系:-

function addresses()
{
    return $this->hasMany(Address::class, 'id1', 'id1');
}

现在在您的用户 Controller 中,您可以获取像这样的用户地址(区域)

$users = User::with('addresses')->get();
dd($users->toArray());

这将打印类似这样的内容

[
    {
        id1: 1,
        name: abaa
        pwd: 12345
        addresses: [
            {
                id2: 1,
                id1: 1,
                area: 2
            },
            {
                id2: 2,
                id1: 1,
                area: 3
            },
            {
                id2: 3,
                id1: 1,
                area: 3
            }
        ]
    },
    {
        ...
    }
]

其次你可以使用 Laravel 关系:-

$builder = new User;
$builder->join('addresses','users.id1','=','addresses.id1')
    ->selectRaw("users.*, GROUP_CONCAT(DISTINCT addresses.area SEPARATOR ',') as distinct_areas")
    ->groupBy("users.id1")
    ->get();

这个查询会给你这样的结果

[
    {
        id1: 1,
        name: abaa,
        pwd: 12345,
        distinct_areas: 2,3
    },
    {
        ...
    }
]

我想这会对你有帮助。

关于mysql - 检索满足第一个表条件的所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55844335/

相关文章:

mysql - sql获取最常用的记录

php - 尝试在 View 上访问 Auth::user()->name 时尝试获取非对象 [Laravel] 的属性

php - Laravel 5.7 - 为什么以编程方式列出控制台命令返回 0?

php - Laravel MongoDB 重载属性的间接修改

php - Laravel 5.4 字段没有默认值

mysql - 查找MySQL数据库某个表列中的所有字符?

php - 显示URL内容

mysql - 子查询返回空值但无法使用它

mysql - 将 MySQL 迁移到另一台新服务器时是否需要 ibdata1、ib_logfile0、ib_logfile1 文件?

PHP 7.1 货币计算