我是laravel的新手,我遇到了一些麻烦。我尝试获取存储在两个不同表中的数据并显示它们:
News.php(型号)
public static function Data($category) {
$perPage = config('var.news.perPage');
if ($category) {
$news = News::orderBy('id', 'desc')->where('category', $category)->SimplePaginate($perPage);
} else {
$news = News::orderBy('id', 'desc')->SimplePaginate($perPage);
}
return $news;
}
这就是我从News表中获取所有数据的方法,结构是:
id, title, body, created_at updated_at, created_by, updated_by, category
类别列包含以逗号分隔的值,例如1,2,3,4
现在,我有另一张表,News_Cat,其中包含id, name
列。
在另一种方法中,我尝试使用存储在News表的category列中的值来获取过滤器名称
public static function getFilterNames($id) {
$filters = DB::table('News_Cat')
->select('News_Cat.name as name')
->leftJoin('News', DB::raw('CAST(News_Cat.id as nvarchar)'), DB::raw('ANY(SELECT(News.category))'))
->where('News.id', $id)
->get();
return $filters;
}
但是,它完全不起作用。我试图实现的是在view.blade中显示过滤器名称作为News_Cat中指定过滤器的“名称”值
@if($news->count())
@foreach($news as $article)
<a href="{{ route('news.show', $article->id) }}" class="item angled-bg" data-filters="{{ $filters }}">
<div class="row">
因此,我会得到例如data-filters="news, update, hot, latest">
而不是data-filters =“1,2,3,4”>
谢谢
你应该使用雄辩!
在你的新闻模型中
public function getFiltersAttribute(){
$categories = explode(',', $this->category);
return implode(', ', NewsCat::find($categories)->pluck('name')->toArray());
}
那么在你看来:
{{ $article->filters }}
将输出news, update, hot, latest
但
您应该在类别和新闻之间使用数据透视表,这会更容易。此方法不允许您急切加载关系并为每条新闻发出请求
如果你不能改变你的数据库结构,我可以建议你:
在AppServiceProvider的boot方法中:
Config::set('tags', NewsCat::all());
然后
public function getFiltersAttribute(){
$categories = explode(',' $this->category);
return implode(', ', config('tags')->whereIn('id', $categories)->pluck('name')->toArray());
}
许多方法
我正在使用laravel命名约定:
news,categories_news(数据透视)和类别
您将拥有2个模型:New和Category
在你的新模型中
public function categories(){
return $this->belongsToMany(Category::class)
}
在您的类别模型中:
public function news(){
return $this->belongsToMany(New::class);
}
如果你没有使用laravel命名约定,你将必须自定义这样的关系:qazxsw poi