Laravel 5.4多态关系不起作用

时间:2017-06-01 18:46:35

标签: php mysql laravel polymorphism

目前正试图在Laravel 5.4中使用Polymorphic关系。

我试图用这几行转储所有“父对象”(映射)的json:

$mappings = Mapping::all();
return $mappings->toJson();

但是,对$this->mappingable的调用只会返回NULL。即使使用以下方式访问单个模型:

$mapping = Mapping::find(1);
$title_mapping = $mapping->mappingable; //Still NULL

查看使用Debugbar进行的查询时,我只看到以下查询:select * from mappings where mappings.id = '1' limit 1。这似乎是错误的,因为查询也应该从其他表中获取信息,不应该吗?

我尝试使用的模型的源代码如下:

Relation::morphMap([
    'title' => 'App\TitleMapping',
    'year' => 'App\YearMapping',
]);

class Mapping extends Model
{
    protected $connection = 'mappings_mysql';
    //

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

    public function jsonSerialize()
    {
        $arr = $this->toArray();
        return array_merge($arr, $this->mappingable->toArray());
    }

}

class TitleMapping extends Model {
    protected $table = "title_mappings";

    protected $connection = 'mappings_mysql';

    public function mapping()
    {
        return $this->morphOne('App\Mapping', 'mappingable', "mapping_type", "mapping_id"); //No difference between App\Mapping and App/Mapping
    }
}

class YearMapping extends Model {
    protected $table = "year_mappings";

    protected $connection = 'mappings_mysql';

    public function mapping()
    {
        return $this->morphOne('App\Mapping', 'mappingable', "mapping_type", "mapping_id");
    }
}

为表创建语法如下所示:

-- Create syntax for TABLE 'mappings'
CREATE TABLE `mappings` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `tmdbid` int(11) NOT NULL,
  `imdbid` varchar(9) NOT NULL DEFAULT '',
  `report_count` int(11) NOT NULL,
  `locked` tinyint(11) NOT NULL DEFAULT '0',
  `total_reports` int(11) NOT NULL,
  `mapping_type` varchar(20) NOT NULL DEFAULT '',
  `mapping_id` int(11) unsigned NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4;

-- Create syntax for TABLE 'title_mappings'
CREATE TABLE `title_mappings` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `aka_title` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4;

-- Create syntax for TABLE 'year_mappings'
CREATE TABLE `year_mappings` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `aka_year` smallint(4) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4;

0 个答案:

没有答案