尝试在我的模型中为用户帐户和朋友创建关系。
从这个例子开始工作,https://github.com/masom/li3_microblog,但我最终得到一个错误,我认为这表明在 Friends 表中找不到字段 user_id,我没有在任何地方指定字段。
这是我的 MySQL 表:
users friends
----- -------
id id ( just the primary key )
username uid ( foreign key to users.id )
friend_uid ( foreign key to users.id )
用户模型:
namespace app\models;
class Users extends \lithium\data\Model {
public $hasMany = array('Friends' => array('keys'=>array('id'=>'uid')));
}
朋友型号:
namespace app\models;
class Friends extends \lithium\data\Model {
public $belongsTo = array(
'Friend' => array('to'=>'app\models\Users','keys'=>array('friend_uid'=>'id')),
'User' => array('to'=>'app\models\Users','keys'=>array('uid'=>'id'))
);
}
用户控制器.php
namespace app\controllers;
use app\models\Users;
use app\models\Friends;
class UsersController extends \lithium\action\Controller {
public function index() {
$conditions = array('Users.id'=>$this->request->id);
$with = array('Friends');
$user = Users::find('first',compact('conditions','with'));
$conditions = array('Friends.friend'=>$user->id);
$with = array('Friend');
$friends = Friends::all(compact('conditions','with'));
return compact('user','friends');
}
}
有了这个我得到一个致命错误,它试图在 Friends 表中找到一个字段 user_id :
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Friends.user_id' in 'on clause'' in /Users/path/Documents/mamp_root/name/libraries/lithium/data/source/database/adapter/MySql.php:
谁能告诉我哪里出错了?