我使用的是 CakePHP 3.7.7,并且我的 Posts 和 Tags 模型之间有一个有效的 belongsToMany 关联。在我的帖子视图中,我设法通过包含列出了所有相关的标签并且一切都按预期工作。
但是,在主要帖子内容下方,我需要显示一些“相关帖子”建议。
我一直在寻找答案,我认为解决方案可能是使用match,但我无法为我的查询获得所需的结果。
我的模型:
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 对应的正确数组。
我怎样才能让它工作?或者更好的选择是什么?