当我尝试运行查询时收到此错误。
BadMethodCallException Call to undefined method Illuminate\Database\Query\Builder::with()
我的搜索 Controller ,根据 URI http://localhost:8000/search/projects/email_category/foo@foo.com_spel+kod-game+code 在数据库中查找特定项目
class SearchController extends BaseController {
//foo.com/search/project/email_category/foo@foo.com-admin@foo.com_spel+kod-game+code
public function index($option, $key, $val){
$keys = explode('_', $key);
$vals = explode('_', $val);
$data = [];
for($i = 0; $i < sizeof($keys); $i++){
$data[$keys[$i]] = explode('-', $vals[$i]);
}
$json = json_encode($data);
echo "<pre>" . $option . ": " . $json . "</pre>";
// Get all rows in option table, but we are going to sort things out before calling it with ->get();
$table = DB::table($option);
foreach($data as $key => $value){
foreach($value as $string){
$split = explode('+', $string);
foreach ($split as $explode){
if(end($split) !== $explode){
switch($key){
case 'email':
$table->with(array('User' => function($query) use ($key, $explode){
$query->where('email',"=",$explode);
}));
break;
case 'categories':
$table->Category->where('typ',"=",$explode);
break;
default:
$table->where($key,"=",$explode);
break;
}
}
}
switch($key){
case 'email':
$table->with(array('User' => function($query) use ($explode){
$query->orWhere('email',"=",$explode);
}));
break;
case 'categories':
$table->Category->orWhere('typ',"=",$explode);
break;
default:
$table->orWhere($key,"=",$explode);
break;
}
}
}
$table->get(); // Runs the query we have build up.
}
}
用户模型
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = array('password', 'remember_token');
public function project()
{
return $this->hasMany('Project');
}
public function experience()
{
return $this->hasMany('Experience');
}
public function reference()
{
return $this->hasMany('Reference');
}
public function stat()
{
return $this->hasMany('Stat');
}
}
项目模型
<?php
class Project extends Eloquent
{
protected $table = 'projects';
public function user()
{
return $this->belongsToMany('User');
}
public function category()
{
return $this->hasMany('Category');
}
public function stat()
{
return $this->hasMany('Stat');
}
}
我尝试遵循 Laravels 网页上的一些示例。 我做了一个测试字符串查询,显示了正确的字符串,但现在我在 ORM 中需要它。我已经尝试自己解决这个问题好几天了,而且我以前从未在 Stackoverflow 上发布过任何内容,所以如果您发现不清楚的地方,只需评论,我会添加它。
最佳答案
我不知道这是否能解决所有问题,但对于初学者来说,请使用您的模型而不是 DB::table()
:
// ...
$model = studly_case($option);
$table = new $model;
// ...
关于php - Laravel 4.2 ORM 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28559676/