mariadb Laravel - MorphTo关系返回空值

vdzxcuhz  于 2022-11-08  发布在  其他
关注(0)|答案(2)|浏览(153)

我在一个Article模型和3个模型(CompanyGroupUser)之间有一个多态关系,有时会返回null
在90%的情况下,可冠词关系是完全正确的,如下所示:


# relations: array:1 [▼

    "articleable" => App\Models\User {#1443 ▼
      #connection: "mysql"
      #table: "users"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: false
      #with: array:2 [▶]
      #withCount: []
      +preventsLazyLoading: false
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #escapeWhenCastingToString: false
      #attributes: array:7 [▶]
      #original: array:7 [▶]
      #changes: []
      #casts: []
      #classCastCache: []
      #attributeCastCache: []
      #dates: array:1 [▶]
      #dateFormat: null
      #appends: array:1 [▶]
      #dispatchesEvents: []
      #observables: []
      #relations: array:2 [▶]
      #touches: []
      +timestamps: true
      #hidden: array:2 [▶]
      #visible: []
      #fillable: []
      #guarded: array:1 [▶]
      #rememberTokenName: "remember_token"
    }
  ]

但有时(1 / 10 ~),其关系是null


# relations: array:1 [▼

    "articleable" => null
  ]

但是,我的模型的属性看起来非常好:


# attributes: array:8 [▼

    "id" => "e5db380f-9516-491f-bf5d-c13eb2978eac"
    "articleable_type" => "App\Models\User" ←
    "articleable_id" => "20e00040-477b-44c5-800f-629a2380afe3" ←
    "title" => "Between yourself and me.' 'That's the most."
    "content" => "Alice. 'And ever since that,' the Hatter went on, spreading out the verses the White Rabbit interrupted: 'UNimportant, your Majesty means, of course,' the Mock  ▶"
    "image_url" => "https://via.placeholder.com/640x480.png/005511?text=non"
    "created_at" => "2022-07-27 11:51:01"
    "updated_at" => "2022-07-27 11:51:01"
  ]

我的数据库确实有记录(从我的users表中导出的JSON):

[
  {
    "id": "20e00040-477b-44c5-800f-629a2380afe3",
    "email": "carolanne.mayer@example.net",
    "email_verified_at": "2022-07-27 11:51:01",
    "password": "$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi",
    "remember_token": "3gRso464ST",
    "created_at": "2022-07-27 11:51:01",
    "updated_at": "2022-07-27 11:51:01"
  }
]

我的模型如下所示:

使用者:

App\Models\User ..........................................
  Database ........................................... mysql
  Table .............................................. users

  Attributes ................................... type / cast
  id unique ..................................... string(36)
  email unique, fillable ....................... string(255)
  email_verified_at nullable, fillable . datetime / datetime
  password fillable, hidden .................... string(255)
  remember_token nullable, fillable, hidden .... string(100)
  created_at nullable, fillable ........ datetime / datetime
  updated_at nullable, fillable ........ datetime / datetime
  type appended .................................. attribute

  Relations ................................................
  profile HasOne .................... App\Models\UserProfile
  companies BelongsToMany ............... App\Models\Company
  groups BelongsToMany .................... App\Models\Group
  page MorphOne ............................ App\Models\Page
  articles MorphMany .................... App\Models\Article
  notifications MorphMany  Illuminate\Notifications\DatabaseNotification

公司名称:

App\Models\Company .......................................
  Database ........................................... mysql
  Table .......................................... companies

  Attributes ................................... type / cast
  id unique ..................................... string(36)
  name fillable ................................. string(60)
  description nullable, fillable ............... text(65535)
  created_at nullable, fillable ........ datetime / datetime
  updated_at nullable, fillable ........ datetime / datetime
  type appended .................................. attribute

  Relations ................................................
  page MorphOne ............................ App\Models\Page
  articles MorphMany .................... App\Models\Article

群组:

App\Models\Group .........................................
  Database ........................................... mysql
  Table ............................................. groups

  Attributes ................................... type / cast
  id unique ..................................... string(36)
  name fillable ................................. string(60)
  description nullable, fillable ............... text(65535)
  created_at nullable, fillable ........ datetime / datetime
  updated_at nullable, fillable ........ datetime / datetime
  type appended .................................. attribute

  Relations ................................................
  page MorphOne ............................ App\Models\Page
  articles MorphMany .................... App\Models\Article

这些型号使用以下HasArticles特性:

<?php

namespace App\Models\Traits;

use App\Models\Article;
use Illuminate\Database\Eloquent\Relations\MorphMany;

trait HasArticles
{
    /**
     * Return model's articles.
     *
     * @return MorphMany
     */
    public function articles(): MorphMany
    {
        return $this->morphMany(Article::class, 'articleable');
    }
}

文章

App\Models\Article .......................................
  Database ........................................... mysql
  Table ........................................... articles

  Attributes ................................... type / cast
  id unique ..................................... string(36)
  articleable_type fillable .................... string(255)
  articleable_id fillable ....................... string(36)
  title fillable ................................ string(70)
  content fillable .................................... text
  image_url nullable, fillable ................. string(255)
  created_at nullable, fillable ........ datetime / datetime
  updated_at nullable, fillable ........ datetime / datetime

  Relations ................................................

Article模型具有以下MorphTo关系:

public function articleable(): MorphTo
{
    return $this->morphTo(__FUNCTION__, 'articleable_type', 'articleable_id');
}

我的create_articles_table迁移(向上架构):

Schema::create('articles', function (Blueprint $table) {
    $table->uuid('id')->primary();
    $table->uuidMorphs('articleable');
    $table->string('title', '70');
    $table->longText('content');
    $table->string('image_url')->nullable();
    $table->timestamps();
});

我正在使用以下代码在控制器中进行调试:

$articles = Article::query()
    ->with('articleable')
    ->inRandomOrder()
    ->first();

dd($articles, $articles->articleable?->toArray());

我错过了什么吗?谢谢你的帮助。
环境:

PHP: 8.1
Laravel: 9.22
Nginx
MariaDB 10.7.4
ua4mk5z4

ua4mk5z41#

问题是你需要把first()方法从with('articleable ')中分离出来,我已经检查过了,看起来像是以某种方式修改了查询。不要用with(),而是在得到结果后使用load。

$articles = Article::query()
    ->inRandomOrder()
    ->first();
$articles->load('articleable');// try to add a check if $articles return null
ee7vknir

ee7vknir2#

原来解决方案是不使用\Str::uuid()(它使用Ramsey\Uuid\Uuid::uuid4())来创建我的模型的UUID,而是使用Ramsey\Uuid\Uuid::uuid6()来代替。没有更多的问题,现在一切都很好。

相关问题