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

标签 mysql sql laravel laravel-4 query-builder

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

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

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/

相关文章:

mysql - Sql 为选择创建正确的查询

sql - 无CTE的分层查询

php - LARAVEL -> 为什么 try catch 在 Laravel 中不起作用?

html - 如何将图像放在标题laravel中

mysql - 检查日期/时间冲突 MySQL

mysql - 修复 MySQL COUNT 查询中的错误

java - HQL语言如何像代码一样连接查询两个表

php - Laravel - 没有模型的查询结果

php - 无论返回结果如何,MYSQL/PHP 分页显示 9 页

mysql - 将 MySQL 中的错误消息语言翻译为印地语