【发布时间】:2019-11-16 09:41:59
【问题描述】:
我使用的是 CakePHP 3.7.7,并且我的 Posts 和 Tags 模型之间有一个有效的 belongsToMany 关联。在我的帖子视图中,我设法通过 contain 列出了所有相关的标签,一切都按预期进行。
但是,在主要帖子内容下方,我需要显示一些“相关帖子”建议。
我一直在寻找答案,我认为解决方案可能是使用匹配,但我无法获得我想要的查询结果。
我的模特:
class PostsTable extends Table
{
public function initialize(array $config)
{
parent::initialize($config);
$this->setTable('posts');
$this->setDisplayField('name');
$this->setPrimaryKey('id');
$this->belongsToMany('Tags', [
'foreignKey' => 'post_id',
'targetForeignKey' => 'tag_id',
'joinTable' => 'posts_tags',
'dependant' => false
]);
}
}
class TagsTable extends Table
{
public function initialize(array $config)
{
parent::initialize($config);
$this->setTable('Tags');
$this->setDisplayField('title');
$this->setPrimaryKey('id');
$this->belongsTo('Tags', [
'foreignKey' => 'tag_id',
'joinType' => 'INNER'
]);
$this->belongsToMany('Posts');
}
}
class PostsTagsTable extends Table
{
public function initialize(array $config)
{
parent::initialize($config);
$this->setTable('posts_tags');
$this->setDisplayField('id');
$this->setPrimaryKey('id');
$this->belongsTo('Posts', [
'foreignKey' => 'post_id',
'joinType' => 'INNER'
]);
$this->belongsTo('Tags', [
'foreignKey' => 'tag_id',
'joinType' => 'INNER'
]);
}
}
还有我的控制器:
class PostsController extends AppController
{
public function view($slug = null)
{
$post = $this->Posts->findBySlug($slug)
->contain(['Tags'])
->first();
$this->set('post', $post);
}
}
我尝试在我的视图函数中添加这个:
$relId = $post->Tags->id;
$related = $this->Posts->find('all')
->contain(['PostsTags','Tags'])
->matching('PostsTags', function(\Cake\ORM\Query $query) use ($post) {
return $query->where([
'PostsTags.tag_id' => $relPost
]);
})
->limit(3)
->execute();
$this->set('relatedPosts', $related);
...但这不起作用。我不断收到错误通知:
注意(8):试图获取非对象的属性
所以我显然无法获得与当前帖子相关的标签 id 对应的正确数组。
我怎样才能让它工作?或者更好的选择是什么?
【问题讨论】:
标签: cakephp associations query-builder cakephp-3.7