Laravel表关系

jus*_*tin 4 php database laravel-4

我有3张桌子:

users
leads
users_leads
Run Code Online (Sandbox Code Playgroud)

users桌子上:

---------------
-- id | name --
-- 1  | doe  --
-- 2  | joe  --
---------------
Run Code Online (Sandbox Code Playgroud)

leads桌子上:

----------------
-- id | type  --
-- 1  | house --
-- 2  | condo --
-- 3  | house --
----------------
Run Code Online (Sandbox Code Playgroud)

users_leads桌子上:

----------------------------
-- id | user_id | lead_id --
-- 1  | 1       | 1       --
-- 1  | 1       | 2       --
-- 1  | 2       | 3       --
----------------------------
Run Code Online (Sandbox Code Playgroud)

然后我有我的模特:

User.php
Lead.php
UsersLead.php
Run Code Online (Sandbox Code Playgroud)

在model/UsersLead.php上

class UsersLead extends Eloquent {
   public function leads()
   {
      return $this->belongsTo('Lead');
   }
}
Run Code Online (Sandbox Code Playgroud)

在model/Lead.php上

class Lead extends Eloquent {
   public function userslead()
   {
      return $this->hasMany('UsersLead');
   }
}
Run Code Online (Sandbox Code Playgroud)

然后我试着运行它:

$data = Lead::all()->userslead;
Run Code Online (Sandbox Code Playgroud)

Laravel抛出这个错误:

Undefined property: Illuminate\Database\Eloquent\Collection::$userslead
Run Code Online (Sandbox Code Playgroud)

如何使用雄辩的ORM运行查询.获得属于特定用户的所有潜在客户?

有人可以帮忙吗?谢谢.

Ana*_*nam 7

你需要多对多的关系:

在您的用户模型中:

class User extends Eloquent {

    public function leads()
    {
        return $this->belongsToMany('Lead');
    }

}
Run Code Online (Sandbox Code Playgroud)

在您的Lead模型中:

class Lead extends Eloquent {

    public function users()
    {
        return $this->belongsToMany('User');
    }

}
Run Code Online (Sandbox Code Playgroud)

然后从您的控制器: 利用多对多的关系.

$leads = User::find(1)->leads;
Run Code Online (Sandbox Code Playgroud)

重要:

需要三个数据库表,这种关系:users,leads,和lead_user.该lead_user表源自相关模型名称的字母顺序,应具有列user_idlead_id列.

参考:

http://laravel.com/docs/eloquent#many-to-many

迭代项目

foreach ($leads as $lead)
{
    dd($lead);
}
Run Code Online (Sandbox Code Playgroud)

更多信息:

http://laravel.com/docs/eloquent#working-with-pivot-tables