【问题标题】:Getting specific columns with eager loading laravel 4使用急切加载 laravel 4 获取特定列
【发布时间】:2014-11-12 10:43:57
【问题描述】:

我是 laravel 的新手,并制作了一个基本应用程序来掌握关系。我已经实现了一对一的关系,并希望从基表和相关表中获取特定的列。我有两个表,即用户和identity_cards.Relationship 定义如下

class User extends Eloquent implements UserInterface, RemindableInterface {

    use UserTrait, RemindableTrait;

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

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

    protected $fillable = array('first_name','last_name','email','created_at','updated_at');

    public function identity_cards() 
    {
        return $this->hasOne('IdentityCard');
    }
}


class IdentityCard extends Eloquent {

    protected $table    = 'identity_cards';
    protected $fillable = array('issuance_date','expiry_date','issuance_location','user_id');
    public $timestamps  = false;

    public function user()
    {
       return $this->belongsTo('User');
    }
}

当我尝试检索所有列时一切正常

$users = User::with('identity_cards')->get()->toArray();

但是当我尝试从一个或两个表中获取特定列时,我得到了一个针对身份证表记录的空数组

 $users = User::with(array('identity_cards'),function($query) {
                $query->select('issuance_location'); //getting specific column from identity card table
              }
          )->get(array("first_name"))->toArray();

上述说法的结果如下:-

Array
(
    [0] => Array
    (
        [first_name] => User1
        [identity_cards] => 
    )

    [1] => Array
    (
        [first_name] => User2
        [identity_cards] => 
    )

    [2] => Array
    (
        [first_name] => User3
        [identity_cards] => 
    )

 )

这可以使用查询生成器来实现,但我想要具有 eloquent 的解决方案。为什么即使我的相关表中有数据,我也会得到一个空数组。如何使用预先加载获取特定列?

【问题讨论】:

    标签: laravel laravel-4 eloquent eager-loading


    【解决方案1】:

    1 您需要始终选择关系的父级primary key 和子级foreign key,否则Eloquent 将无法匹配相关模型。

    2 传递给预加载的闭包是数组的值,而不是with 函数的第二个参数:

    User::with(array('identity_cards' => function($query) {
                $query->select('issuance_location', 'user_id');
          }))->get(array('first_name', 'id'))->toArray();
    

    3 我会将该关系重命名为 identity_card,因为它是 hasOne - 使用起来会更容易。

    【讨论】:

    • 标记为正确答案,以防其他人有同样的问题。
    【解决方案2】:

    其中一个解决方案就是建立一个与您所做的类似的新关系,但为了方便起见,稍微调整一下:

    public function identity_cards_limited() 
        {
            return $this->hasOne('IdentityCard')->select('desired_column');
        }
    

    【讨论】:

    • 我看到了这个选项,但是当我想为一个查询检索一组列并为另一个查询检索另一组列时,这将限制我的范围。例如,在一个场景中,我需要 id 和到期日期卡和其他场景,我只需要发行日期。对于具有更多列的表,这将是指定许多列名的开销。但是是的,这也是一个不错的选择:)。感谢您的帮助:)
    猜你喜欢
    • 2014-08-13
    • 2020-01-13
    • 1970-01-01
    • 1970-01-01
    • 2021-01-21
    • 2015-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多