Last active
December 10, 2015 08:38
-
-
Save rc1021/4408800 to your computer and use it in GitHub Desktop.
PHP Activerecord 多對多自我參照( has_many through[many to many] self referential )
Codeigniter How to solution
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Alias 用戶關注的資料表 | |
*/ | |
class TargetUser extends User | |
{ | |
static $table_name = "users"; | |
} | |
/** | |
* Alias 用戶粉絲的資料表 | |
*/ | |
class FromUser extends User | |
{ | |
static $table_name = "users"; | |
} | |
class User extends ActiveRecord\Model | |
{ | |
static $has_many = array( | |
// 用戶的關注 | |
array('idols_user_references', 'class_name' => "UserReference", 'foreign_key' => "from_user_id"), | |
array('idols', 'class_name' => "TargetUser", 'through' => 'idols_user_references', 'foreign_key' => "from_user_id"), | |
// 用戶的粉絲 | |
array('fans_user_references', 'class_name' => "UserReference", 'foreign_key' => "target_user_id"), | |
array('fans', 'class_name' => "FromUser", 'through' => 'fans_user_references', 'foreign_key' => "target_user_id"), | |
); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class User extends ActiveRecord\Model | |
{ | |
static $has_many = array( | |
// 用戶的關注 | |
array('idols_user_references', 'class_name' => "UserReference", 'foreign_key' => "from_user_id"), | |
array('idols', 'class_name' => "User", 'through' => 'idols_user_references', 'foreign_key' => "from_user_id"), | |
// 用戶的粉絲 | |
array('fans_user_references', 'class_name' => "UserReference", 'foreign_key' => "target_user_id"), | |
array('fans', 'class_name' => "User", 'through' => 'fans_user_references', 'foreign_key' => "target_user_id"), | |
); | |
} | |
$user = User::first(); | |
$user->fans; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment