CakePHP 3:如何与一条记录建立关联?

时间:2016-10-02 12:20:26

标签: php cakephp orm cakephp-3.0 model-associations

我想通过locations_ways连接表与Locations建立联系,包括顺序和点(开始/中间/结束)。

最后我想得到联想 地点 - 所有地点 end_location仅限结束位置 start_location仅开始位置

现在对于end_location和start_location,我有一个包含一条记录的数组。但我不想写这样的:$ way-> end_location [0] - > name;

如何处理?

class WaysTable extends Table
{
    public function initialize(array $config)
    {
         $this->belongsToMany('Locations', [
            'through' => 'LocationsWays',
            'sort' => ['LocationsWays.position ASC'],
        ]);
        $this->belongsToMany('LocationStartPoint', [
            'className' => 'Locations',
            'foreignKey' => 'way_id',
            'targetForeignKey' => 'location_id',
            'through' => 'LocationsWays',
            'conditions' => ['LocationsWays.point' => 'start'],
        ]);
        $this->belongsToMany('LocationEndPoint', [
            'className' => 'Locations',
            'foreignKey' => 'way_id',
            'targetForeignKey' => 'location_id',
            'through' => 'LocationsWays',
            'conditions' => ['LocationsWays.point' => 'end'],
        ]);
    }
}

class LocationsTable extends Table
{
    public function initialize(array $config)
    {
        $this->belongsToMany('Ways', [
            'through' => 'LocationsWays',
        ]);
    }
}

class LocationsWaysTable extends Table
{
    public function initialize(array $config)
    {
        $this->belongsTo('Ways', [

        ]);
        $this->belongsTo('Locations', [

        ]);
    }
}

获取功能。

public function getWayById($id, $locale = 'uk')
    {
        I18n::locale($locale);

        $item = $this->find()
            ->where(['Ways.id' => $id])
            ->contain(['Locations', 'LocationStartPoint', 'LocationEndPoint'])
            ->cache(function (Query $q) {
                return 'way-' . md5(serialize($q->clause('where')));
            }, 'orm')
            ->first();

        return $item;
    }

0 个答案:

没有答案