1

Larvel 8 我在这里需要一些帮助.. 我不知道错误在哪里?

->>> 当我在 TINKER 中写“$article->tags;”时,我得到了“null”

修补匠(她是错误的):??????????

创建_tags_tabels.php:

标签.php:

文章.php:

数据库表-> tablePlus "article_tag" :

数据库表-> tablePlus“标签”:

当我尝试将标签链接到“Show.blade.php”文件中的文章时,这会在下一集稍后引发错误。

4

4 回答 4

1

首先,Laravel 的名称约定应该像table = users then一样单数,model = User所以你应该将文章更改为文章

在您的Article模型中,第二个属于关系的名称发生了变化tags to tag,因为文章属于标签而不是标签,tags如果它是 HasMany Relation,您将使用

第三,您似乎应该在修补程序中急切地加载模型的关系,如下所示

$article = App\Models\Articles::with('tags')->first();
//then
$article->tags
于 2021-03-03T17:14:02.580 回答
1
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中的项目和克隆链接 链接

于 2021-04-24T22:20:43.887 回答
0

我找到了 :

1-articles_tag 到 article_tags

@r89human 2- 在 Articles.php > Tags 函数(belongsToMany)

它像这样对我有用^^

@Khaled

我之所以这样做,是因为我不得不更改所有项目约定名称。

...终于它现在起作用了。

于 2021-03-03T22:53:37.083 回答
0

尝试在您的文章模型中使用。

public function tags(){
    return $this->belongsToMany(Tag::class, 'article_tag', 'article_id', 'tag_id');
 }
于 2021-03-03T19:49:21.210 回答