【问题标题】:Laravel eloquent add extra models to hasManyLaravel eloquent 为 hasMany 添加额外的模型
【发布时间】:2015-09-11 19:32:42
【问题描述】:

我有一个user 模型,每个用户有多个licenses。有 2 个默认许可证适用于不在 licenses 表中的所有用户,它们需要使用 User 模型中包含的某些数据动态创建。

如何在每次获取用户许可证时创建 2 个许可证并将其添加到 licenses() 的输出中?

class User extends Model implements AuthenticatableContract, CanResetPasswordContract {

    use Authenticatable, CanResetPassword;

    protected $table = 'users';
    public $timestamps = false;

    protected $fillable = ['name', 'email', 'password'];

    protected $hidden = ['password', 'remember_token'];

    public function licenses()
    {
        return $this->hasMany('App\License', 'user_id', 'id')->where('deleted', '=', '0');
    }
}

【问题讨论】:

  • 在没有反馈的情况下投反对票,非常有帮助
  • 这些额外的许可证存储在哪里?
  • 创建用户时为什么不将它们添加到许可证表中?您可以在EventProvider 中执行此操作。
  • @max.lanin 无论如何都不会存储它们,但是User 模型具有一些与这些默认许可证相关的属性。
  • @Jerodev 我正在使用现有系统,我想尝试在不以任何方式修改系统的情况下进行操作

标签: laravel eloquent laravel-5


【解决方案1】:

您可以在调用许可证的模型中创建一个额外的函数并添加额外的许可证。

记得测试你使用这个功能的所有地方,这样就不会发生奇怪的事情了。

<?php

class User extends Model implements AuthenticatableContract, CanResetPasswordContract {

    use Authenticatable, CanResetPassword;

    protected $table = 'users';
    public $timestamps = false;

    protected $fillable = ['name', 'email', 'password'];

    protected $hidden = ['password', 'remember_token'];

    // HasMany function
    public function _licenses()
    {
        return $this->hasMany('App\License', 'user_id', 'id')->where('deleted', '=', '0');
    }

    // New licenses function
    public function licenses() 
    {
        // Get licenses from database
        $licenses = $this->_licenses;

        // Add  other lisences
        $licenses = $licenses->add(new License([ "user_id" => $this->id, "name" => "foo" ]));
        $licenses = $licenses->add(new License([ "user_id" => $this->id, "name" => "bar" ]));

        // Return the new collection
        return $licenses
    }
}

【讨论】:

  • 谢谢。我确实尝试过类似的事情,因为我认为$this-&gt;hasMany 返回了一个集合,但显然它没有。我刚试过你的答案,我得到了Call to undefined method Illuminate\Database\Query\Builder::add()
  • 哦,我的错,你必须在没有()的情况下调用$this-&gt;_licenses,这将返回集合。
  • 哦,很高兴知道如何归还收藏品。不幸的是,这引发了另一个错误Call to undefined method Illuminate\Database\Eloquent\Collection::addEagerConstraints()
  • 你能显示你正在使用的确切代码吗?你能把它放在pastebin什么的吗?
  • 当然,这是用户模型 - laravel.io/bin/d9LaP#53 这是控制器 - laravel.io/bin/Kky38
猜你喜欢
  • 2015-04-04
  • 2021-07-07
  • 1970-01-01
  • 2018-08-05
  • 2019-11-16
  • 1970-01-01
  • 1970-01-01
  • 2021-07-02
  • 1970-01-01
相关资源
最近更新 更多