我正在使用laravel 5.6版本,这是我的测试模型文件
<?php
namespace App\Model\data\Models;
use Illuminate\database\Eloquent\Model;
class Test extends Model
{
protected $guarded = ['id'];
protected $table = 'tests';
/*
* Test - TestTranslation relation
* Test has many translations
*/
public function translations()
{
return $this->hasMany('App\Model\Data\Models\TestTranslation');
}
/*
* Test - Image relation
* Test can have an thumbnail
*/
public function thumbnails()
{
return $this->morphMany('App\Model\Data\Models\Image', 'type');
}
}
这是我的图片模型
<?php
namespace App\Model\Data\Models;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
protected $guarded = ['id'];
protected $table = 'images';
/*
* Image belongs to Post, Account, Comment
*/
public function type()
{
return $this->morphTo();
}
}
这是我的图像数据库方案表:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateImagesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('images', function (Blueprint $table) {
$table->increments('id');
$table->string('path');
$table->enum('type', ['avatar', 'thumbnail', 'generic'])->default('generic');
$table->integer('type_id')->unsigned()->nullable();
$table->enum('type_type',[
"Account",
"Comment",
"Post",
"Skill",
"Test"
])->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('images');
}
}
在AppServiceProvider中,我将'Test'链接到我的模型文件:
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\ServiceProvider;
use Laravel\Dusk\DuskServiceProvider;
use Illuminate\Database\Eloquent\Relations\Relation;
use App\Model\Data\Models\Account;
use App\Model\Data\Models\EmailChangeConfirmation;
use App\Model\Observers\Common\AccountObserver;
use App\Model\Observers\Common\EmailChangeConfirmationObserver;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Schema::defaultStringLength(191);
Relation::morphMap([
'Account' => 'App\Model\Data\Models\Account',
'Comment' => 'App\Model\Data\Models\Comment',
'Post' => 'App\Model\Data\Models\Post',
'Skill' => 'App\Model\Data\Models\Skill',
'Test' => 'App\Model\Data\Models\Test'
]);
if(env('APP_ENV') != 'testing') {
Account::observe(AccountObserver::class);
EmailChangeConfirmation::observe(EmailChangeConfirmationObserver::class);
}
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
if ($this->app->environment('local', 'testing')) {
$this->app->register(DuskServiceProvider::class);
}
}
}
正如你所看到的,我有更多的morhpMany类型,并且它们都运行良好。但由于某种原因,我最近添加的Test关系总是返回一个空集合,即使很难,我确信测试有缩略图。原因: 在这个截图中,我在数据库中有记录,每个测试都有两个图像。他们的ID匹配创建的测试和类型的ID是“测试”。我试图清除所有缓存,运行composer dump-autoload,但没有一个帮助。
也许有人可以帮助识别这里有什么问题?因为正如我之前所说的其他类型的帖子,帐户工作正常。