尝试在我的模型中为用户帐户和朋友创建关系。
使用此示例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'))
);
}
UsersController.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:
谁能告诉我哪里出错了?
答案 0 :(得分:2)
看起来该教程是一年前最后更新的。我知道在某些时候配置选项从'keys'
更改为'key'
,因此您可以尝试。