我刚接触过拉里威尔,遇到了一些麻烦。我试图获取存储在两个不同表中的数据,并显示它们:
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表分类列中的值获取筛选器名称
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">,而不是数据过滤器=“1,2,3,4”>“
谢谢
发布于 2017-12-20 21:53:24
你应该用雄辩!
在你的新闻模式中
public function getFiltersAttribute(){
$categories = explode(',', $this->category);
return implode(', ', NewsCat::find($categories)->pluck('name')->toArray());
}那么在你看来:
{{ $article->filters }}将输出news, update, hot, latest
但
你应该在你的分类和新闻之间使用一个枢轴表,这样就容易多了。此方法不能允许您急切地加载关系并为每个新闻发出请求
如果您不能更改数据库结构,我可以建议您:
在AppServiceProvider的引导方法中:
Config::set('tags', NewsCat::all());然后
public function getFiltersAttribute(){
$categories = explode(',' $this->category);
return implode(', ', config('tags')->whereIn('id', $categories)->pluck('name')->toArray());
}多到多方法
我在餐桌上使用的是拉拉命名约定:
新闻、categories_news (枢轴)和类别
你将有两个模型:新的和类别
在你的新模型中
public function categories(){
return $this->belongsToMany(Category::class)
}在您的类别模型中:
public function news(){
return $this->belongsToMany(New::class);
}如果您不使用laravel命名约定,则必须按以下方式自定义这些关系:https://laravel.com/docs/5.5/eloquent-relationships#many-to-many
https://stackoverflow.com/questions/47913882
复制相似问题