我正在与SlimPHP和Eloquent合作开展一个项目。 我试图在Model的方法中运行RAW SQL查询,如下所示:
/models/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。
上面的代码告诉我:
致命错误:在非对象中调用成员函数select() /vagrant/vendor/illuminate/support/Illuminate/Support/Facades/Facade.php 在第208行
在这种情况下,文档非常有帮助,您能否对此有所了解?
感谢
答案 0 :(得分:11)
仔细阅读setup instructions on 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');
答案 1 :(得分:1)
另外,如果你需要进行原始查询,那么在bootEloquent()之后调用setAsGlobal()会有所帮助
$capsule->addConnection($sqliteDb);
$capsule->bootEloquent();
$capsule->setAsGlobal(); // <--- this
答案 2 :(得分:0)
在 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);
}
}