2 回答
TA贡献1824条经验 获得超8个赞
问题是你没有在你的帖子表中保存CATEGORY_ID,保存好类别 ID 并尝试这样:
更新 POST 模型:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
//Table Name
protected $table = 'posts';
// Setup fields of table "posts"
protected $fillable = ['id', 'title', 'body', 'cover_image','category_id'];
//Model Relationships
public function tag(){
return $this->belongsToMany('App\Tag', 'id');
}
// Relation category to foreign key
public function category() {
return $this->belongsTo('App\Category','category_id');
}
}
类别模型
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $table = 'categories';
// Setup fields of table "category"
protected $fillable = ['id', 'display_name', 'name', 'key'];
//Model Relationships
public function posts()
{
return $this->hasMany('App\Post');
}
}
看法
@if(count($posts) > 0)
@foreach($posts as $post)
<span> <i class="fa fa-folder-open"></i> {{ $post->category->display_name }} </span>
@endforeach
@endif
移民帖 - 外键 category_id
Schema::create('posts', function (Blueprint $table) {
// Your other fields.....
// You must setup category like this
$table->integer('category_id')->nullable()->unsigned();
$table->foreign('category_id')->references('id')->on('categories')->onUpdate('cascade')->onDelete('cascade');
});
控制器
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
class PagesController extends Controller
{
public function index()
{
$posts = Post::all();
if (!empty($posts)) {
// Please let me know this test
dd($posts[0]->category->display_name);
return view('pages.index', ['posts' => $posts]);
}
else {
return view('pages.empty');
}
}
TA贡献1865条经验 获得超7个赞
我认为您post()
在Category
模型中的方法有误。尝试像这样修改这个方法:
类别型号:
public function post() { return $this->hasMany('App\Post', 'id');}
- 2 回答
- 0 关注
- 128 浏览
添加回答
举报