从雄辩的关系中选择特定的列 [英] Select specific columns from Eloquent relations

查看:66
本文介绍了从雄辩的关系中选择特定的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following models in my application:

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

现在我正在尝试运行以下查询:

Now i am trying to run the following query:

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

现在我要做的就是从我的 users 表和 first_name customer_details 表中的 last_name ,但是每当我尝试执行此操作时,它总是以 null 的形式返回 customer_details .此功能将仅在一页上使用,这意味着可能还有其他页面可能需要所有详细信息,但并不需要这一页,因此我想创建一个单独的Eloquent关系来做到这一点.

Now what I want it to do is to select only the email and phone number from my users table and first_name, last_name from my customer_details table but whenever I try this it always returns customer_details as null. This function will be used on one page alone meaning there are other pages that may require all details but not this one so I want to create a separate Eloquent relation to do this.

推荐答案

您需要在选择的内容中包含id,否则急切的加载将无可匹敌.我只是针对自己的项目对此进行了测试,并遇到了同样的问题,将id添加到选择中即可解决该问题.

You need to include the id in your select, otherwise the eager loading has nothing to match against. I just tested this against my own project and ran into the same issue, adding the id to the select fixes it.

$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,则在第二个调用中或附加时没有任何匹配项.

To further explain this, eager loading works by making your parent call first (in this case, the call to users) and then doing a second call like SELECT * FROM customer_details WHERE customer_details.user_id IN (?) where ? is a list of user IDs. It then loops through the results from that second call and attaches them to the appropriate user objects. Without the id on the user objects, there's nothing to match against in the second call or when attaching.

编辑

要从热切加载的表中选择特定的列,可以使用

To select specific columns from an eagerly loaded table, you can use the closure capabilities explained here. So you use the relationship name as the key and a closure that receives a Builder object as the value, like so:

$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不知道如何连接两者

Note that you must select the relationship column for both, otherwise Laravel has no idea how to connect the two

这篇关于从雄辩的关系中选择特定的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆