如何在laravel控制器中创建sql连接语句

41zrol4v  于 2021-06-17  发布在  Mysql
关注(0)|答案(2)|浏览(298)

我有两张table customer_idtbl_customer 以及 tbl_stocks 已连接到同一数据库。关于这个问题,我的逻辑是joinsql语句。
这是针对laravel和mysql的,到目前为止,我已经在php上尝试过了,效果很好,但是当我在laravel上实现它时,我不知道为什么?
这是我的php代码,想把它转换成laravel,但我不知道放在哪里?我要把它放在视图中还是控制器中

$query = "SELECT c.*, s.* FROM tbl_customer c JOIN tbl_stock s ON s.customer_id = c.customer_id AND c.customer_id = 1";

控制器

$data = DB::table('tbl_customer')
            ->join ......  //Im not sure about this 
            ->select ....  // neither this 
            ->get();

            print_r($data)

模型
我的模型上没有代码
路线

Route::get('/admin/shopcontrol', 'Admin\ShopsController@testquery');

我期望在一个简单的过程中获取或获取值的查询或结果 echo 并且fetch连接已连接

6tdlim6h

6tdlim6h1#

你查过拉维尔的网站了吗?
https://laravel.com/docs/5.7/queries#joins
它有一个可以用来重新组织代码的演示。
如下所示。
连接内部连接子句
查询生成器也可用于编写连接语句。要执行基本的“内部联接”,可以对查询生成器示例使用联接方法。传递给join方法的第一个参数是需要联接到的表的名称,而其余参数指定联接的列约束。当然,如您所见,您可以在一个查询中联接到多个表:

$users = DB::table('users')
            ->join('contacts', 'users.id', '=', 'contacts.user_id')
            ->join('orders', 'users.id', '=', 'orders.user_id')
            ->select('users.*', 'contacts.phone', 'orders.price')
            ->get();

如果合适的话,你可以在那里找到更多的信息。

s4n0splo

s4n0splo2#

试试这个:

$data = DB::table('tbl_customer')
                ->join('tbl_stock', 'customer_id', '=', 'tbl_customer.customer_id')
                ->select('tbl_customer.*', 'tbl_stock.*')
                ->where('customer_id', '=', 1) 
                ->get();

相关问题