从一个

时间:2016-06-09 12:24:42

标签: php laravel eloquent

目前在我们使用直接sql查询的一个项目中,决定删除它们并实现ORM,因此我们决定使用 Illuminate Eloquent Model 组件为了那个原因。由于我们对此不熟悉,因此我对两个相互关联的模型之间的关系知之甚少。

当前的sql查询

select * from login as A, user_profile as B where A.user_id = B.login_id and A.user_id = $user_id

我创建了两个模型,一个User延伸Illuminate\Database\Eloquent\Model,另一个UserProfile延伸Illuminate\Database\Eloquent\Model。模型实现就像这样

用户模型

<?php
namespace App\Project;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected $table = 'login';

    protected $primaryKey = 'user_id';

    public function profile()
    {           
        return $this->hasOne('App\Project\UserProfile', 'login_id');
    }   
}

UserProfile模型

<?php
namespace App\Project;

use Illuminate\Database\Eloquent\Model;

class UserProfile extends Model
{
    protected $table = 'user_profile';

    protected $primaryKey = 'id';

    public function user()
    {   
        return $this->belongsTo('App\Project\User', 'user_id');
    }
}

我使用方法Manage的课程getUserInfo以user_id作为输入

管理班级

<?php
namespace App\Project;

class Manage
{
    public function getUserInfo($id)
    {
        return (new User())->profile()->where('login_id', $id)->get();      
    }
}

当我在应用程序中调用此方法时,我得到空集合

Illuminate\Database\Eloquent\Collection Object
(
    [items:protected] => Array
        (
        )
)

但如果我在这样的两个陈述中打破它

$user = User::find($id);
$profile = $user->profile()->where('login_id', $id)->get();

$user变量中,我得到User模型的对象,其中包含登录表的数据,在$profile变量中,我得到了UserProfile模型的对象,其中包含user_profile表的数据。现在我无法理解如何使用Eloquent模型在单个调用中获得两个表的结果。

3 个答案:

答案 0 :(得分:3)

你可以这样做:

$user = User::find($id)->with('profile');

with条款中,您应该提供关系的名称。这将填充您关系的对象。

答案 1 :(得分:2)

有两种选择:

1

如果你想获得jointy查询结果,请尝试使用这样的DB面:

$usersWithProfiles = \DB::table('users')
    ->distinct()
    ->join('profiles', 'profiles.user_id', '=', 'users.id')
    ->get();

这将为您提供每行中用户及其个人资料的完整列表。

2

如果您想使用Eloquent,只需访问以下个人资料:

$user->profile;

这将自动查询配置文件关系,因为您已在用户的模型中定义了关联方法:profile()

答案 2 :(得分:1)

好的,使用where代替find能够获得单一记录时得到了答案。

$user = User::where('user_id', $id)->with('profile')->get();