如何使多态性[封闭式]。

问题描述 投票:1回答:1

我已经试过了,我仍然看到一个错误的Pivot请建议做什么,我已经卡住了两天亮相这段代码。

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Answer extends Model
{
    protected $fillable = ['body', 'user_id'];

    public function question()
    {
        return $this->belongsTo(Question::class);
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function getBodyHtmlAttribute()
    {
        return \Parsedown::instance()->text($this->body);
    }

    public static function boot()
    {
        parent::boot();

        static::created(function ($answer) {
            $answer->question->increment('answers_count');                     
        });        

        static::deleted(function ($answer) {            
            $answer->question->decrement('answers_count');            
        });
    }

    public function getCreatedDateAttribute()
    {
        return $this->created_at->diffForHumans();
    }

    public function getStatusAttribute()
    {
        return $this->isBest() ? 'vote-accepted' : '';
    }

    public function getIsBestAttribute()
    {
        return $this->isBest();
    }

    public function isBest()
    {
        return $this->id === $this->question->best_answer_id;
    }

    public function votes()
    {
        return $this->morphedToMany(User::class, 'votable');
    }

    public function upVotes()
    {
        return $this->votes()->wherePivot('vote', 1);
    }

    public function downVotes()
    {
        return $this->votes()->wherePivot('vote', -1);
    }
}
php laravel-5 polymorphism
1个回答
0
投票

I你有两个类A和B,你想做一个多态关系。

在A类中

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

b类

public function a()
 {
   return $this->morphOne('App\A', 'atable');
 }
© www.soinside.com 2019 - 2024. All rights reserved.