【问题标题】:morphTo function returns null, although relationship existsmorphTo 函数返回 null,尽管存在关系
【发布时间】:2019-10-03 11:15:15
【问题描述】:

我创建了一个多态关系,它有效。就在尝试检索“父级”(使用with)时,结果是null

假设有一些表/模型需要特殊关系进行缓存。

迁移

class CreateSearchCachesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('search_caches', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->text('searchable');
            $table->string('url');
            $table->morphs('searchCacheable');
            $table->timestamps();
        });
    }
}

型号

class SearchCache extends Model
{
    protected $fillable = [
        'searchable',
        'url'
    ];

    public function searchCacheable()
    {
        return $this->morphTo();
    }
}

使用$model->searchCache()->save($searchCache); 保存有效。

但在尝试检索关系时,它显示为 null:

$results = SearchCache::query();

        foreach ($search as $searchString) {
            $results = $results->where('searchable', 'like', "%$searchString%");
        }

        $results = $results->with('searchCacheable')->get();

        dd($results);

【问题讨论】:

    标签: laravel eloquent polymorphism


    【解决方案1】:

    问题似乎在于在名称中使用 CamelCase。所以请注意先检查一下。

    searchCacheable 重命名为searchcacheable 修复了它。

    【讨论】:

      猜你喜欢
      • 2017-08-05
      • 1970-01-01
      • 2016-03-22
      • 2018-03-09
      • 2012-04-12
      • 1970-01-01
      • 1970-01-01
      • 2016-03-22
      • 1970-01-01
      相关资源
      最近更新 更多