Laravel 5 Scope以及其他查询

时间:2016-10-06 09:14:14

标签: php laravel

我想根据网址向特定网页展示内容。 所以通过调用url mypage.com/menues/{city}我想要显示所有餐馆的特定信息。

我有这条路线:

Route::get('menues/{city?}', 'PagesController@menue');

这个控制器:

public function menue($city = null) {

  if ($city) {
    $restaurants = User::with(['articles' => function ($q){
      $q->nowpublished()->where('city', '=', 'Heilbronn');
    }])->get();
  } else {
    $restaurants = User::with(['articles' => function ($q){
      $q->nowpublished();
    }])->get();
  }

  return view('pages.menues')->withRestaurants($restaurants)                             
                             ->withCity($city);


}

我在文章模型中定义了这个范围:

  public function scopeNowPublished($query) {
    $zero = Carbon::today()->addHours(23)->addMinutes(59)->addSeconds(59);
    $query->whereBetween('published_at',[Carbon::today(),$zero])->orderBy('published_at','desc');
}

使用上面的代码抛出QueryException。

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'city' in 'where clause' (SQL: select * from `articles` where `articles`.`user_id` in (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) and `published_at` between 2016-10-06 00:00:00 and 2016-10-06 23:59:59 and `city` = Heilbronn order by `published_at` desc)

我不确定我是否可以使用where子句链接nowpublished()...

不幸的是我不知道如何解决这个问题。

3 个答案:

答案 0 :(得分:1)

文章是否有字段city?我认为User有这样的解决方案是让where方法调出关系查询:

$restaurants = User::with(['articles' => function ($q){
  $q->nowpublished();
}])
->where('city', 'Heilbronn')
->get();

答案 1 :(得分:0)

从错误中查看查询:

Column not found: 1054 Unknown column 'city' in 'where clause'

(SQL: 
    select *
    from `articles`
    where `articles`.`user_id` in (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)
    and `published_at` between 2016-10-06 00:00:00 and 2016-10-06 23:59:59
    and `city` = Heilbronn
    order by `published_at` desc
)

我猜这是代表PHP代码的这一部分:

'articles' => function ($q){
  $q->nowpublished()->where('city', '=', 'Heilbronn');
}

它正在查找表city上的列articles

那么问题是articles表格是否有city列?

你在问题​​中说:

  

我想向所有餐馆展示特定的城市

但是你甚至没有查询任何Restaurant类型的实体,我看到的只有UserArticle。也许您错过了问题的Restaturant部分问题?由于我们不知道您的数据库架构,因此很难说!

修改

回答你提出的另一个问题......

public function menue($city = null)
{
  // prep query so we don't write it twice
  $query = User::with(['articles' => function ($q){
      $q->nowpublished();
    }]);

  // Check city exists with users
  $city = User::where('city', $city)->get();

  // if it does then apply where
  if ($city) {
    $query->where('city', '=', $city)->get();
  }

  // get results from query
  $restaurants = $query->get();

  // return view with query results
  return view('pages.menues')
    ->withRestaurants($restaurants)
    ->withCity($city);

}

答案 2 :(得分:0)

我已将代码更新为

if ($city) {
    $restaurants = User::with(['articles' => function ($q){
      $q->nowpublished();
    }])->where('city', '=', $city)->get();
  } else {
    $restaurants = User::with(['articles' => function ($q){
      $q->nowpublished();
    }])->get();
  }

如果我在我的数据库列中调用了一个城市的网址,则不会显示任何结果且该网页为空。如果城市与数据库条目匹配,如何显示所有条目。