在控制器中,我得到了这个:
$this->Site1->post_id=$id;
$this->set('posts', $this->Site1->read());
当我用这行代码替换它时: $ this-> set('posts',$ this-> Site1-> read('post_id',$ id));
但是返回的结果完全不同。
它们之间有什么区别吗?
是否可以通过将这两行代码重写为一行代码来使这两行代码整洁?
$this->Site1->post_id=$id;
$this->set('posts', $this->Site1->read());
答案 0 :(得分:2)
结果完全不同,因为您告诉read()
方法仅提取post_id
列。当你将一个字符串作为第一个参数传递给read()
时会发生这种情况。您还可以传递一组列作为第一个参数,或null
来获取所有列。第二个参数是您要检索的记录的ID。有关示例,请参阅documentation。
是否可以通过将这两行代码重写为一行代码来使这两行代码整洁?
如果您想将其全部放在一行,请尝试:$this->set('posts', $this->Site1->read(null, $id);
答案 1 :(得分:1)
作为另一种选择,您也可以简单地使用findBy
$this->set('posts', $this->Site1->findByPostId($id));