关于belongssto的模型关联

时间:2013-04-17 06:18:25

标签: cakephp

以前我使用的是cakephp版本1.3.1,模型关联工作正常,但在版本2.3.2中,关联不起作用。

我创建了一个名为Listings的控制器:

class ListingsController extends AppController {
    var $uses = 'Listing';
    var $name = 'Listings';
    var $components = array();

    function getFeatured(){
        $listing = $this->Listing->read();
        $this->Listing->recursive = 1;
        $today = date('Y-m-d');
        $listings = $this->Listing->find('all', array('conditions'=>'Listing.featured_expiration >='.$today,'order'=>'Rand()'));
        return $listings;
    }

//**** Function For Retreve All Properties Counts **** //
}

在我创建的模特中

class Listing extends AppModel {
    var $name = 'Listing';
    var $displayField = 'full_address';
    var $belongsTo = array(
        'User' => array(
            'className' => 'User',
            'foreignKey' => 'user_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),      
    );    
}

但我没有收到用户表记录。

它在本地工作正常。我也试过使用可包含的行为,但遇到了同样的问题。

由于

1 个答案:

答案 0 :(得分:0)

不是答案,而是一些改进代码的评论。我发布这个作为答案,因为评论允许有限的空间;

不要将var用于属性

Var用于旧版本的CakePHP以与PHP 4兼容。对于PHP5,使用publicprotectedprivate明确设置其visibility

您发布的代码中的所有属性都应为public,因此可以更改为;

 public $name = 'Listing';
 public $displayField = 'full_address';
 //etc

删除关系中不必要的选项

在您的示例中,空选项仅添加“混乱”(有时甚至可能导致不必要的副作用)。删除fieldsconditionsorder选项。

更进一步,因为您的模型显然遵循CakePHP约定,所以您根本不必设置任何选项;这两个都可以正常工作:

public $belongsTo = array(
    'User' => array(),
);

甚至:

public $belongsTo = array('User');

删除未使用的查询

为什么要在getFeatured()内执行两个查询?第一个查询($listing = $this->Listing->read();)的结果甚至没有使用,可以删除

数据相关代码应在您的模型中执行。

方法getFeatured()实际上不属于Controller。更糟糕的是,因为它是 public 方法,所以可以通过浏览器访问它! (通过http://yourdomain.com/listings/getFeatured/)如果找不到视图文件,它可能会显示错误,但方法中的查询将被执行

将方法移至Listing模型。你将不得不做一些小修改;

class Listing extends AppModel {
    // rest of the code here 

    public function getFeatured(){
        //Moved this to within the 'find' parameters
        //to only change recursive for *this* find
        //and not influence other queries after running
        //this one
        //$this->recursive = 1;

        return $this->find('all', array(
            'conditions' => array(
                // NOTE: use an associative array here
                'Listing.featured_expiration >=' => date('Y-m-d'),
            ),
            'recursive' => 1,

            // NOTE: check if this really works
            //      Cake *may* treat this as a literal
            //      value (string "Rand()")
            'order' => 'Rand()'
        ));
    }
}

现在,如果您想在控制器中使用它,请使用:

$this->Listing->getFeatured();