簡體   English   中英

在 Slim PHP 中使用 RAW Eloquent 查詢

[英]Use RAW Eloquent Queries with Slim PHP

我正在使用 SlimPHP 和 Eloquent 進行一個項目。 我正在嘗試在模型的方法中運行 RAW SQL 查詢,如下所示:

/模型/Form.php

<?php
namespace models;

class Form extends \Illuminate\Database\Eloquent\Model {

protected $table = 'forms';

public function getResponses($form_id)
{
    // HERE
    $select = \Illuminate\Support\Facades\DB::select('select 1');
    return 1;
}

}

我正在使用 Capsule 來引導 ORM。

上面的代碼給了我:

致命錯誤:在第 208 行的 /vagrant/vendor/illuminate/support/Illuminate/Support/Facades/Facade.php 中的非對象上調用成員函數 select()

在這種情況下,文檔很有幫助,你能解釋一下嗎?

謝謝

仔細閱讀github 上設置說明,並確保正確遵循它們。


對於 Capsule,您應該使用Illuminate\\Database\\Capsule\\Manager或作為DB “Facade”。

$select = \Illuminate\Database\Capsule\Manager::select('select 1');

我通常導入它並定義一個別名:

use Illuminate\Database\Capsule\Manager as DB;

// ...

$select = DB::select('select 1');

另外,如果您需要進行原始查詢,在 bootEloquent() 之后調用 setAsGlobal() 可能會有所幫助

$capsule->addConnection($sqliteDb);
$capsule->bootEloquent();
$capsule->setAsGlobal();   // <--- this

在 Slim 4 中,我們可以使用 $this->getConnection()->select($sql);

 <?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;


class Product extends Model{

    protected $table = 'products';
    public $timestamps = false;

    protected $fillable = ["name", "price", "quantity", "supplier", "image", "category"];

    public function getProductsByCategory(){
        $sql = 'SELECT p.id,
                        p.name,
                        p.price,
                        p.quantity,
                        p.supplier,
                        p.image,
                        p.category,
                (SELECT IF(COUNT(*) >= 1, TRUE, FALSE) FROM favorite f WHERE f.user_id = 1 AND f.product_id = p.id) AS isFavourite,
                (SELECT IF(COUNT(*) >= 1, TRUE, FALSE) FROM carts c WHERE c.user_id = 1 AND c.product_id = p.id) AS isInCart
                FROM products p';

        return $this->getConnection()->select($sql);
    }   
} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM