多态关系未在数据库中插入模型类型

问题描述

在我的Laravel应用程序中,我可以报告不同的模型,因此我正在使用多态关系。帖子,主题解决方案是可报告的,可以为MorphedToMany。当我尝试在控制器中创建新报告时,出现General error: 1364 Field 'reportable_id' doesn't have a default value (sql: insert into `reports` (`channel`,`updated_at`,`created_at`) values ({"id":18,"created_at":"2020-08-20T09:37:06.000000Z","updated_at":"2020-08-20T09:37:06.000000Z","name":"marketing"},2020-08-21 09:13:45,2020-08-21 09:13:45))错误

我按照教程中的文档进行操作,但找不到错误

这是我的代码,以post类为例

发布


use Illuminate\Database\Eloquent\Model;
use Cog\Contracts\love\Reactable\Models\Reactable as ReactableContract;
use Cog\Laravel\love\Reactable\Models\Traits\Reactable;

class Post extends Model implements ReactableContract
{
    /**
     * @var mixed
     */

    use Reactable;

    protected $fillable=['title','body'];
    protected $guarded=[];

    public  function user(){
        return $this->belongsTo('App\User');
    }
    public function tags(){
        return $this->belongsToMany('App\Tag');
    }
    public function channel(){
        return $this->belongsTo('App\Channel');
    }
    public function comments(){
        return $this->hasMany('App\Comment');
    }
    public function reports(){
        return $this->morphToMany('App\Report','reportable');
    }
}

报告


use Illuminate\Database\Eloquent\Model;

class Report extends Model
{
    protected $guarded=[];

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

reportController


use App\Comment;
use App\Post;
use App\Report;
use App\Solution;
use App\Thread;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ReportController extends Controller
{
    public function create(){

        switch (\request('table')){
            case 'posts':
                $model=Post::find(\request('model'));
                break;
            case 'threads':
                $model=Thread::find(\request('model'));
                break;

            case 'solutions':
                $model=Solution::find(\request('model'));
                //for Now we are not implementing comments since is gonna be more complicated
        }

        //save model into database
        $report=new Report();
        $report->channel=$model->channel->name;
        $model->reports()->create(['channel'=>$model->channel]);
        //notify user
        //redirect to channel
    }
}

解决方法

解决了我使用MorphToMany而不是MorphMany