gpt4 book ai didi

laravel - 从 Eloquent 关系中选择特定列

转载 作者:行者123 更新时间:2023-12-03 19:13:47 25 4
gpt4 key购买 nike

我的应用程序中有以下模型:

用户.php

<?php namespace App\Models;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Kodeine\Acl\Traits\HasRole;

class User extends Model implements AuthenticatableContract, CanResetPasswordContract {

use Authenticatable, CanResetPassword, HasRole;

/**
* The database table used by the model.
*
* @var stringSS
*/
protected $table = 'users';

/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['name', 'email', 'password', 'is_active'];

/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = ['password', 'remember_token'];

public function customer_details()
{
return $this->hasOne('App\Models\CustomerDetails', 'user_id');
}

}

CustomerDetails.php
<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class CustomerDetails extends Model {

protected $table = 'customer_details';
protected $dates = ['created_at', 'updated_at', 'deleted_at'];
protected $appends = ['full_name'];

public function getFullNameAttribute()
{
return $this->attributes['first_name'] .' '. $this->attributes['last_name'];
}

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

public function invoices() {
return $this->hasMany('App\Models\Invoices', 'customer_id');
}
}

现在我正在尝试运行以下查询:
$user = User::select('email', 'phone')->where('id', Auth::user()->id)->with('customer_details')->first();

现在我想要它做的是只选择 邮箱 电话 我的号码 用户 表和 名字 , 姓氏来自我的 customer_details 表,但每当我尝试此操作时,它总是返回 customer_details 为空。这个函数将单独在一个页面上使用,这意味着还有其他页面可能需要所有细节,但不是这个,所以我想创建一个单独的 Eloquent 关系来做到这一点。

最佳答案

您需要包含 id在您的选择中,否则急切加载无法匹配。我刚刚针对我自己的项目对此进行了测试并遇到了同样的问题,添加了 id选择修复它。

$user = User::select('id', 'email', 'phone')->where('id', Auth::user()->id)->with('customer_details')->first();

为了进一步解释这一点,预先加载的工作原理是首先调用您的父调用(在这种情况下,调用 users )然后进行第二次调用,例如 SELECT * FROM customer_details WHERE customer_details.user_id IN (?)哪里 ?是用户 ID 的列表。然后它遍历第二次调用的结果并将它们附加到适当的用户对象。没有 id在用户对象上,在第二次调用或附加时没有任何可匹配的内容。

编辑

要从急切加载的表中选择特定列,您可以使用解释的闭包功能 here .因此,您使用关系名称作为键和接收 Builder 的闭包。对象作为值,如下所示:
$user = User::select('id', 'email', 'phone')
->where('id', Auth::user()->id)
->with('customer_details' => function (Builder $query) {
$query->select('id', 'user_id', 'name', 'foo');
})
->first();

注意一定要为两者选择关系列,否则Laravel不知道如何将两者连接起来

关于laravel - 从 Eloquent 关系中选择特定列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32727060/

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