gpt4 book ai didi

php - 从两个相关的 Illuminate Eloquent 模型中获取数据

转载 作者:可可西里 更新时间:2023-11-01 00:30:02 26 4
gpt4 key购买 nike

目前在我们使用直接 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\数据库\Eloquent\模型。模型实现是这样的

用户模型

<?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');
}
}

用户文件模型

<?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 作为输入

管理类(class)

<?php
namespace App\Project;

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

当我在应用程序中调用此方法时,我得到了Empty Collection

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 模型在一次调用中获得两个表的结果。

最佳答案

你可以这样做:

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

with 子句中,您应该输入您的关系名称。这将填充您的关系对象。

关于php - 从两个相关的 Illuminate Eloquent 模型中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37725954/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com