gpt4 book ai didi

mysql - 如何将同一个表中的多行合并为 1 行,在 sql 连接中使用 laravel 查询生成器的不同列

转载 作者:行者123 更新时间:2023-11-29 03:30:35 24 4
gpt4 key购买 nike

美好的一天,(抱歉,标题令人困惑,很难表达:))

我有一个包含以下字段的交易表:

Transactions TABLE
ID | amount | branch_id | supplier_id
1 | 1,200 | 2 | 1

Subsidiary TABLE
ID | Name | Type
1 | supplier1 | 0
2 | branch_2 | 1

现在我想在我的 View 中正确显示它的 id 值,所以我加入了下表(我使用 laravel 查询构建器)

$transactions = DB::table('transactions_table')
->leftJoin('subsidiary_table','transactions_table.supplier_id','=','subsidiary_table.id')
->get(array('transactions_table.id',
'transactions_table.amount',
'subsidiary_table.name as branch',
'subsidiary_table.name as supplier'));

我很困惑我怎样才能得到这个结果

Display View
ID | Ammount | Supplier | Branch
1 | 1,200 | Supplier1 | branch_2

谢谢你的澄清..

最佳答案

为 View 创建迁移

没有直接的方法可以使用 Laravel 的 Eloquent/QueryBuilder 方法创建 sql View 。您需要创建一个迁移,在其中运行 MySql 的普通 CREATE VIEW 命令。

正如在 Laravel.io thread 上讨论的那样

Since there are no methods that use the database drivers to create views, you could just create it using SQL syntax.

MySQL example:

DB::statement('CREATE VIEW example_view_name AS SELECT field1, field2 FROM table WHERE field1 > field2');

您需要在 up() 中的迁移中运行此代码

public function up()
{
//db statement for creating view
}

SQL 查询

您的 SQL 查询生成问题已在 dba.stackexchange 上得到解答

  SELECT  t.ID,  t.amount,  s.Name as Supplier,  sb.Name as Branch FROM
Transactions as t JOIN Subsidiary as s ON (s.ID=t.supplier_id) JOIN
Subsidiary as sb ON (sb.ID=t.branch_id) WHERE t.ID = 1; Try it.

PD: You can change the JOIN syntax for LEFT JOIN if you want to return the t.ID = 1 record from Transactions even if one column don't match in Subsidiary's JOINs.

SQL View 模型

现在您必须像创建任何数据库表一样创建模型。然后拿Eloqeunt的特权

Display::all()

并且您拥有 Eloquent 对象的集合。

关于mysql - 如何将同一个表中的多行合并为 1 行,在 sql 连接中使用 laravel 查询生成器的不同列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31228483/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com