laravel 预加载
2018年6月26日1.在模型定义方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?php namespace App\Models; class Topic extends Model { protected $fillable = ['title', 'body', 'user_id', 'category_id', 'reply_count', 'view_count', 'last_reply_user_id', 'order', 'excerpt', 'slug']; public function category() { return $this->belongsTo(Category::class); } public function user() { return $this->belongsTo(User::class); } } |
2在控制器中使用预加载
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?php . . . class TopicsController extends Controller { . . . public function index() { $topics = Topic::with('user', 'category')->paginate(30); return view('topics.index', compact('topics')); } . . . } |
3.在视图中调用模型的方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
@if (count($topics)) <ul class="media-list"> @foreach ($topics as $topic) . . . {{ $topic->user->name }} # . . . {{ $topic->category->name }} . . . @endforeach </ul> @else <div class="empty-block">暂无数据 ~_~ </div> @endif |