尽管存在关系,但morphTo函数返回null

时间:2019-10-03 11:15:15

标签: laravel eloquent polymorphism

我创建了一个有效的多态关系。只是当尝试检索“父”(使用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);进行保存是有效的。

enter image description here

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

$results = SearchCache::query();

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

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

        dd($results);

enter image description here

1 个答案:

答案 0 :(得分:0)

问题似乎出在名称中使用CamelCase。因此,请先检查一下。

searchCacheable重命名为searchcacheable可以解决此问题。