The*_*pha 51
你可以试试这个:
// query can't be select * from table where
Model::select(DB::raw('query'))->get();
Run Code Online (Sandbox Code Playgroud)
一个例子:
Model::select(DB::raw('query'))
->whereNull('deleted_at')
->orderBy('id')
->get();
Run Code Online (Sandbox Code Playgroud)
此外,您可以使用类似的东西(使用查询生成器):
$users = DB::table('users')
->select(DB::raw('count(*) as user_count, status'))
->where('status', '<>', 1)
->groupBy('status')
->get();
Run Code Online (Sandbox Code Playgroud)
此外,您可以尝试这样的事情(使用查询生成器):
$users = DB::select('select * from users where id = ?', array(1));
$users = DB::select( DB::raw("select * from users where username = :username"), array('username' => Input::get("username")));
Run Code Online (Sandbox Code Playgroud)
Raw-Expressions在Laravel网站上查看更多相关信息.
小智 11
用DB::statement('your raw query here').希望这可以帮助.
Ork*_*nov 11
您可以使用hydrate()函数将数组转换为Eloquent模型,该模型Laravel本身在内部用于将查询结果转换为模型。据我所知,文档中没有提到它。
下面的代码等同于$userModels = User::where('id', '>', $userId)->get();:
$userData = DB::select('SELECT * FROM users WHERE id > ?', [$userId]);
$userModels = User::hydrate($userData);
Run Code Online (Sandbox Code Playgroud)
hydrate()函数定义\Illuminate\Database\Eloquent\Builder为:
/**
* Create a collection of models from plain arrays.
*
* @param array $items
* @return \Illuminate\Database\Eloquent\Collection
*/
public function hydrate(array $items) {}
Run Code Online (Sandbox Code Playgroud)
我不认为你可以默认.我扩展了Eloquent并添加了以下方法.
/**
* Creates models from the raw results (it does not check the fillable attributes and so on)
* @param array $rawResult
* @return Collection
*/
public static function modelsFromRawResults($rawResult = [])
{
$objects = [];
foreach($rawResult as $result)
{
$object = new static();
$object->setRawAttributes((array)$result, true);
$objects[] = $object;
}
return new Collection($objects);
}
Run Code Online (Sandbox Code Playgroud)
然后你可以做这样的事情:
class User extends Elegant { // Elegant is my extension of Eloquent
public static function getWithSuperFancyQuery()
{
$result = DB::raw('super fancy query here, make sure you have the correct columns');
return static::modelsFromRawResults($result);
}
}
Run Code Online (Sandbox Code Playgroud)
老问题,已经回答了,我知道。
然而,似乎没有人提到 Expression 类。
当然,这可能无法解决您的问题,因为您的问题使得原始条件需要包含在 SQL 中的何处(是在 SELECT 语句中还是在 WHERE 语句中?)不明确。但是,无论如何,您可能会发现这条信息很有用。
在您的模型文件中包含以下类:
use Illuminate\Database\Query\Expression;
Run Code Online (Sandbox Code Playgroud)
然后在 Model 类中定义一个新变量
protected $select_cols = [
'id', 'name', 'foo', 'bar',
Expression ('(select count(1) from sub_table where sub_table.x = top_table.x) as my_raw_col'), 'blah'
]
Run Code Online (Sandbox Code Playgroud)
并添加范围:
public function scopeMyFind ($builder, $id) {
return parent::find ($id, $this->select_cols);
}
Run Code Online (Sandbox Code Playgroud)
然后从您的控制器或逻辑文件中,您只需调用:
$rec = MyModel::myFind(1);
dd ($rec->id, $rec->blah, $rec->my_raw_col);
Run Code Online (Sandbox Code Playgroud)
快乐的时光。
(适用于 Laravel 框架 5.5)
| 归档时间: |
|
| 查看次数: |
69909 次 |
| 最近记录: |