Larvel 8 我在这里需要一些帮助.. 我不知道错误在哪里?
->>> 当我在 TINKER 中写“$article->tags;”时,我得到了“null”
修补匠(她是错误的):??????????
创建_tags_tabels.php:
标签.php:
文章.php:
数据库表-> tablePlus "article_tag" :
数据库表-> tablePlus“标签”:
当我尝试将标签链接到“Show.blade.php”文件中的文章时,这会在下一集稍后引发错误。
首先,Laravel 的名称约定应该像table = users
then一样单数,model = User
所以你应该将文章更改为文章
在您的Article
模型中,第二个属于关系的名称发生了变化tags to tag
,因为文章属于标签而不是标签,tags
如果它是 HasMany Relation,您将使用
第三,您似乎应该在修补程序中急切地加载模型的关系,如下所示
$article = App\Models\Articles::with('tags')->first();
//then
$article->tags
php artisan make:model Articles -m
php artisan make:model Tag -m
php artisan make:migration article_tags_table
public function up()
{
Schema::create('tags', function (Blueprint $table) {
$table->id();
$table->string('name')->unique();
$table->timestamps();
});
}
public function up()
{
Schema::create('articles', function (Blueprint $table) {
$table->id();
$table->string('name')->unique();
$table->timestamps();
});
}
class ArticleTagsTable extends Migration
{
public function up()
{
Schema::create('article_tags', function (Blueprint $table) {
$table->id();
$table->foreignId('articles_id')
->constrained()
->onDelete('cascade');
$table->foreignId('tags_id')
->constrained()
->onDelete('cascade');
$table->unique(['article_id','tag_id']);
$table->timestamps();
});
}
}
gitlab中的项目和克隆链接 链接
尝试在您的文章模型中使用。
public function tags(){
return $this->belongsToMany(Tag::class, 'article_tag', 'article_id', 'tag_id');
}