【问题标题】:Joining two tables in laravel - how to have second table data as a property of result在 laravel 中连接两个表 - 如何将第二个表数据作为结果的属性
【发布时间】:2020-03-25 03:55:06
【问题描述】:

我有两张桌子 A 和 B。

表 A:

no  name  type
1   shoe   1
2   shirt  2
3   book   3

表 B:

type color   size
1    red     big
2    yellow  small
3    blue    medium

当我查询where A.no === 1 and A.type === 1 时,我想获取如下数据:

{
  no: 1,
  name: 'shoe',
  type: 1,
  info: {
    color: 'red',
    size: 'big'
  },
}

我试过这样的:

select a.*, b.* from stores a, types b where a.type = 1 and a.type = b.id

它只返回普通对象,我想得到像上面这样的嵌套数据。 我认为可以使用 join 和执行任何其他查询技巧来完成。

这是我为您准备的 sql fiddle 链接。 http://sqlfiddle.com/#!9/3ad910/2

提前致谢。

【问题讨论】:

  • 是的,我可以使用连接获得内联数据,但想要获得嵌套数据结构。
  • 我打开了一个 sql fiddle 链接,sqlfiddle.com/#!9/3ad910/2
  • 这就是雄辩的关系。

标签: mysql laravel join


【解决方案1】:

模型表A:

public function info()
{
    return $this->hasOne(TableB::class, 'type', 'type');
}

模型表B:

public function tableA()
{
    return $this->belongsTo(TableA::class, 'type', 'type');
}

查询:

TableA::with('info')->where(['type' => 1, 'no' => 1])->get();

【讨论】:

    【解决方案2】:

    因此,您所拥有的查询(尽管使用 1992 年后的查询语法编写得更好)就是您所需要的。剩下的问题是重新排列结果数组的简单案例。我不知道 eloquent/laravel,而且我在重新排列数组方面非常糟糕,但这里有一个例子,我的意思是使用普通的旧 php(也许有人会好心地编写一个更贴切的数组转换)。 ..

    <?php
    
    /*
    DROP TABLE IF EXISTS table_a;
    
    CREATE TABLE table_a
    (no SERIAL PRIMARY KEY
    ,name  VARCHAR(12) UNIQUE
    ,type INT NOT NULL
    );
    
    INSERT INTO table_a VALUES
    (1,'shoe',1),
    (2,'shirt',2),
    (3,'book',3);
    
    DROP TABLE IF EXISTS table_b;
    
    CREATE TABLE table_b
    (type SERIAL PRIMARY KEY
    ,color VARCHAR(12) NOT NULL
    ,size VARCHAR(12) NOT NULL
    );
    
    INSERT INTO table_b VALUES
    (1,'red','big'),
    (2,'yellow','small'),
    (3,'blue','medium');
    
    SELECT a.no
         , a.name
         , b.*
      FROM table_a a
      JOIN table_b b
        ON b.type = a.type
     ORDER
        BY a.no;
    +----+-------+------+--------+--------+
    | no | name  | type | color  | size   |
    +----+-------+------+--------+--------+
    |  1 | shoe  |    1 | red    | big    |
    |  2 | shirt |    2 | yellow | small  |
    |  3 | book  |    3 | blue   | medium |
    +----+-------+------+--------+--------+
    */
    
    require('path/to/connection/stateme.nts');
    
    $query = "
    SELECT a.no
         , a.name
         , b.type
         , b.color
         , b.size
      FROM table_a a
      JOIN table_b b
        ON b.type = a.type
     WHERE a.no = 1
       AND a.type = 1
     ORDER
        BY a.no;
    ";
    
    $result = mysqli_query($db,$query) or die(mysqli_error());
    
    $old_array = array();
    
    while($row = mysqli_fetch_assoc($result)){
    
    $old_array[] = $row;
    
    }
    
    $new_array = array();
    
    foreach ($old_array as $row) {
       $new_array[]['name'] = $row['name'];
       $new_array[$row['no']]['info']['color'] = $row['color'];
       $new_array[$row['no']]['info']['size'] = $row['size'];
    }
    
    $new_array = array_values($new_array); // reindex
    
    
    print_r($new_array);
    
    ?>
    

    输出:

    Array
    (
        [0] => Array
            (
                [name] => shoe
            )
    
        [1] => Array
            (
                [info] => Array
                    (
                        [color] => red
                        [size] => big
                    )
    
            )
    
    )
    

    或者,json_encoded...

    [{"name":"shoe"},{"info":{"color":"red","size":"big"}}]
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-26
    • 2018-05-05
    • 1970-01-01
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多