这是我的控制器代码:
namespace App\Http\Controllers\Dynamic;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Blogs;
use LaravelLocalization;
use App\BlogsCategory;
class BlogsController extends Controller
{
public function main(){
//$posts = new Blogs::where('lang',LaravelLocalization::getCurrent);
$posts = new Blogs;
$data = $posts::where('lang',LaravelLocalization::getCurrentLocale())->where('created_at','<=',NOW())->orderBy('created_at','DESC')->paginate(config('PAGINATOR_COUNTER'));
return view('Dynamics.Blogs.Main',compact('data'));
}
}
这是我的博客模型:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\BlogsCategory;
class Blogs extends Model
{
public function categories()
{
return $this->belongsToMany(BlogsCategory::class);
}
}
和BlogsCategory模型:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Blogs;
class BlogsCategory extends Model
{
public function blogs_data()
{
return $this->belongsToMany(Blogs::class);
}
}
我想获取所有lang col为'fa'的博客帖子,并在其类别中显示。 这是我的查看代码:
@forelse($data as $tmp)
<div class="blog-item-left">
<div class="blog-left-img">
<img src="/upload/blogs/small/{{$tmp->img}}" alt="{{$tmp->title}}" />
</div>
<div class="blog-left-text">
<div class="blog-text">
<span><i class="fas fa-box"></i>
@foreach($data->categories as $cat_data)
{{$cat_data->title}}
@endforeach
</span>
<a href="#"><h4 class="title">{{$tmp->title}}</h4></a>
<p>{{$tmp->description}}</p>
</div>
</div>
</div>
@empty
<h2>No Data to show!</h2>
@endforelse
此代码向我显示此错误:
未定义的属性:Illuminate \ Pagination \ LengthAwarePaginator :: $ categories(视图:/Users/soroush/Sites/msadd/resources/views/Dynamics/Blogs/Main.blade.php)
我必须做什么?
答案 0 :(得分:1)
您只想在查询中加载“类别”关系。
class BlogsController extends Controller
{
public function main(){
//$posts = new Blogs::where('lang',LaravelLocalization::getCurrent);
$data = Blogs::with('categories')
->where('lang',LaravelLocalization::getCurrentLocale())
->where('created_at','<=', now())
->orderBy('created_at','DESC')
->paginate(config('PAGINATOR_COUNTER'));
return view('Dynamics.Blogs.Main',compact('data'));
}
}
并按如下所示更改刀片(视图)模板的“类别”迭代:
@foreach($tmp->categories as $cat_data)
{{$cat_data->title}}
@endforeach