laravel 5.4 - 在雄辩模型中返回精确模型

时间:2017-09-05 14:01:44

标签: php laravel-5.4 laravel-eloquent

我有一个Post模型以及两个TextPostPhotoPost模型。

我想做Post::find(1);这样的事情,如果id=1的记录具有type=photo属性,它应该返回PhotoPost模型的实例,否则应该是一个实例TextPost模型如何在laravel 5.4中做到这一点?我的课程如下:

post.php中

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $fillable = ['file_id', 'file', 'bot_id', 'text'];

    public function bot()
    {
        return $this->belongsTo(Bot::class);
    }
}

TextPost.php

namespace App;

use App\Traits\TextPostTrait;

class TextPost extends Post
{
    use TextPostTrait;

    protected $table = 'posts';

    protected $fillable = ['bot_id', 'text'];

    protected $attributes = ['type' => 'text'];

}

PhotoPost.php

namespace App;

use App\Traits\PhotoPostTrait;

class PhotoPost extends Post
{
    use PhotoPostTrait;

    protected $table = 'posts';

    protected $attributes = ['type' => 'photo', 'image_watermark'];

}

PhotoPostTrait.php

namespace App\Traits;

use App\Scopes\PhotoPostScope;

trait PhotoPostTrait
{
    public static function bootPhotoPostTrait()
    {
        static::addGlobalScope(new PhotoPostScope());
    }
}

TextPostTrait.php

namespace App\Traits;

use App\Scopes\TextPostScope;

trait TextPostTrait
{
    public static function bootSettingsTrait()
    {
        static::addGlobalScope(new TextPostScope());
    }
}

TextPostScope.php

namespace App\Scopes;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\ScopeInterface;

class TextPostScope implements ScopeInterface
{
    public function apply(Builder $builder, Model $model)
    {
        $builder->where('type', 'text');
    }

    public function remove(Builder $builder, Model $model)
    {
    }
}

PhotoPostTrait.php

namespace App\Scopes;

use \Illuminate\Database\Eloquent\Model;
use \Illuminate\Database\Eloquent\Builder;
use \Illuminate\Database\Eloquent\Scope;

class PhotoPostScope implements Scope
{
    public function apply(Builder $builder, Model $model)
    {
        $builder->where('type', '=', 'photo');
    }

    public function remove(Builder $builder, Model $model)
    {
    }
}

所以我使用globalScopes对我的帖子类型进行分类。所以基本上我把它们存放在一张桌子里。所以我应该添加$ table ='帖子&#39 ;;所以laravel不会把它作为一个单独的模型。并使用特征来引导范围。在范围内,我将确保记录为PhotoText

修改

我在https://laracasts.com/discuss/channels/eloquent/multiple-models-to-same-table找到了JarekTkaczyk的解决方案 但我想知道laravel是否解决了这个问题?

0 个答案:

没有答案