【发布时间】:2021-06-21 01:10:35
【问题描述】:
我尝试在 Laravel 中使用 Eloquent 在两个模型之间建立关系,但在我看来,我一直收到一个错误,说它不存在。无法创建关系,因为我的视图无法识别它。这是我的代码。
类别模型
class Categories extends Model
{
use HasFactory;
protected $table = 'categories';
protected $fillables = ['category'];
public function Posts(){
return $this->hasMany(Posts::class);
}
}
后模型
class Posts extends Model
{
use HasFactory;
protected $table = 'posts';
protected $fillables = ['title', 'body', 'image_path', 'views'];
public function Categories(){
return $this->belongsTo(Categories::class);
}
}
类别迁移
class CreateCategoriesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('category');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('categories');
}
}
迁移后
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::dropIfExists('posts');
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('category_id')->unsigned();
$table->string('title');
$table->mediumText('Body')->nullable();
$table->string('image_path');
$table->integer('views');
$table->tinyInteger('published');
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
$table->foreign('category_id')
->references('id')
->on('categories')
->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}```
Code in My View
@foreach ($Categories->帖子为 $post) {{ $post['title'] }} @endforeach```
错误:
【问题讨论】:
-
$Categories->Posts()->get(),我也认为你需要重构你的代码,在模型中是 $fillable,而不是 $fillables。看看 Laravel 的约定,我认为给你一些处理,让你不那么头疼(例如,公共函数 posts() 而不是 Posts())......祝你好运