所以我有三个模型:“不完整”、“用户”和“协作”。它们与外键相关,如下所示:
Collaboration->incomplete_id
incomplete_id->Incomplete
Incomplete->user_id
user_id->User
如果我想获取协作模型用户的电子邮件,我有以下代码
User::find(Incomplete::find($collab->incomplete_id)->user_id)->email);
我觉得这是错误的,因为我没有加入任何表,但我不想脱离 mvc 并从 Controller 直接调用 SQL。基本上我很好奇如何正确地做到这一点。
协作模型
class Collaboration extends Eloquent{
//Set the database to connect to as form d
protected $connection = 'formd';
//Set the table for the model to incomplets
protected $table = 'collaborations';
//Set the fillable columns
protected $fillable = array('incompid', 'link', 'shareFlag');
private $rules = array(
'link'=>'required|unique:collaborations|size:56',
'incompid'=>'required|integer'
);
private $errors;
public function validate($data)
{
// make a new validator object
$v = Validator::make($data, $this->rules);
// check for failure
if ($v->fails())
{
// set errors and return false
$this->errors = $v->errors();
return false;
}
// validation pass
return true;
}
public function errors()
{
return $this->errors;
}
public function getId(){
return $this->getKey();
}
public function incomplete(){
return $this->hasOne('Incomplete');
}
}
模型不完整
class Incomplete extends Eloquent{
//Set the database to connect to as form d
protected $connection = 'formd';
//Set the table for the model to incomplets
protected $table = 'incompletes';
//Set the fillable columns
protected $fillable = array('name', 'data', 'userid');
private $rules = array(
'name' => 'required|min:3',
'data' => 'required'
);
private $errors;
public function validate($data)
{
// make a new validator object
$v = Validator::make($data, $this->rules);
// check for failure
if ($v->fails())
{
// set errors and return false
$this->errors = $v->errors();
return false;
}
// validation pass
return true;
}
public function errors()
{
return $this->errors;
}
public function getId(){
return $this->getKey();
}
public function getData(){
return $this->data;
}
public function getName(){
return $this->name;
}
public function user(){
return $this->hasOne('User');
}
}
最佳答案
您可以使用 Eloquents 关系: http://laravel.com/docs/eloquent#relationships
class Collaboration extends Eloquent {
public function incomplete()
{
return $this->hasOne('Incomplete', 'incomplete_id', 'id');
}
}
然后,您可以通过执行以下操作从不完整的记录中获取数据:
$collab->incomplete->user_id
关于php - Laravel 的新手,想知道我是否正确使用模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23397723/