我在Laravel之外使用雄辩的ORM。我对表和视图执行简单的CRUD操作,但我无法弄清楚如何遍历或设置关系。我试过这段代码
<?php
include 'eloquent_database.php';
class User extends Illuminate\Database\Eloquent\Model {
public $timestamps = false;
protected $table = 'user';
protected $primaryKey = 'userId';
public function company() {
return $this->belongsTo('company', 'companyID');
}
}
// Create the company model
class Company extends Illuminate\Database\Eloquent\Model {
public $timestamps = false;
protected $table = 'company';
protected $primaryKey = 'companyID';
public function users()
{
return $this->hasMany('user', 'userId');
}
}
// Grab all from company table
$companys = Company::all();
foreach ($companys as $company) {
echo "<B>" .$company->name . "<br>";
$users = $company->users();
foreach($users as $user) {
echo $user->userName . "<br>";
}
};
?>
但我没有找回公司的任何用户。只是公司名称
感谢
由于
答案 0 :(得分:1)
就像@Cryode已经说过的那样:
$company->users(); // relation object
$company->users; // collection of related users
所以你需要后者。
然而,你的关系是错误的,所以无论如何它都不会起作用,直到你解决它如下:
// Company model
public function users()
{
return $this->hasMany('user', 'companyId');
}
答案 1 :(得分:0)
您使用的关系不正确。如果要返回关系的结果(即实际模型[s]),则调用属性,而不是方法。
// Will perform a query and return the results of the relationship.
$users = $company->users;
// Will return the relationship object you defined in your method. It's normal PHP, zero magic.
$usersRelationshipObject = $company->users();