1. First on the table and model
1.user user table
{
user_id // Primary
}
2.account accounts table
{
ACCOUNT_ID // primary key
user_id // foreign key user
}
3.User model
class the User the extends the Model { protected $ Table = 'yh_user' ; protected $ PK = 'user_id' ; } 4.Account model class Account the extends the model { protected $ Table = 'yh_account' ; protected $ PK = 'ACCOUNT_ID' ; }
a, if necessary data is acquired by the User Account model models the first step User model Note that many methods created in association are:hasMany () method
class User extends Model
{
protected $table = 'yh_user';
protected $pk = 'user_id';
//关键操作
public function account()
{
return $this->hasMany('Account','user_id');
}
}
Controller Operation
$data = UserModel::with('account')->select();
Output:
[2] => Array (. 3) { [ "user_id"] => int (67) [ "Account"] => Array (. 1) { [0] => Array (2) { [ "ACCOUNT_ID"] => int (. 1) [ "user_id"] => int (67) } }
a, if necessary to obtain the data model User Account first step anti-models created by the model association method is associated Account Note: a belongsTo () method
class Account extends Model
{
protected $table = 'yh_account';
protected $pk = 'account_id';
//关键操作
public function User()
{
return $this->belongsTo('User','user_id');
}
}
Controller operation:
Data $ = AccountModel :: with ( 'the User' ) -> SELECT () ;
the dump ( $ Data ) ;
output:
array(1) { [0] => array(8) { ["account_id"] => int(1) ["user_id"] => int(67) ["user"] => array(11) { ["user_id"] => int(67) } } }