【问题标题】:Laravel Eloquent pass Attribute to RelationshipLaravel Eloquent 将属性传递给关系
【发布时间】:2020-06-18 22:17:44
【问题描述】:

我正在尝试通过急切加载来加载关系。但是,想将属性传递给关系函数。

(Laravel 6.x)

模型 - taxChildren() 需要一个 ID

public function taxChildren($moduleId)
{
    return $this->hasMany($this, 'parent')->where('module', '=', $moduleId')->orderBy('created_at', 'asc');
}

控制器

$departments = tax::where([
        ['module', '=', $this->departmentsModuleId],
    ])
        ->whereNull('parent')
        ->with([
            'taxChildren' => ['moduleId', '2']
        ])
        ->get();

现在,我知道我可以像这样向我的关系传递查询:

$departments = tax::where([
        ['module', '=', $this->departmentsModuleId],
    ])
        ->whereNull('parent')
        ->with([
            'taxChildren' => function($query){
                $query->where('module', '=', $this->departmentsModuleId);
            },
        ])
        ->get();

但我会经常将它用于多个相似的关系。任何人都知道如何实现这一目标?谢谢!

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    您不能将参数直接传递给关系函数,但这可以通过模型属性来完成

    Mymodel.php
    class MyModel extends Model {
        protected $moduleId = null;
    
        public function taxChildren(){
            return $this->hasMany($this, 'parent')->where('module', '=', $this->moduleId)->orderBy('created_at', 'asc');
        }
    }
    
    MyController.php
    use App\MyModel;
    ...
    class MyController extends Controller {
    
        public function controllerMethod(){
            $query = new MyModel;
            $query->moduleId = 1;
    
            $departments = $query::where([
                ['module', '=', $this->departmentsModuleId],
            ])
            ->whereNull('parent')
            ->with(['taxChildren'])
            ->get();
        }
    }
    

    你也可以使用 laravel 查询范围来设置 modelId 属性。我认为这是更简洁的代码

    Mymodel.php
    class MyModel extends Model {
        protected $moduleId = null;
    
        public function scopeMudule($q, $module_id){
            $this->moduleId = $module_id;
            return $q;
        }
    
        public function taxChildren(){
            return $this->hasMany($this, 'parent')->where('module', '=', $this->moduleId)->orderBy('created_at', 'asc');
        }
    }
    
    MyController.php
    use App\MyModel;
    ...
    class MyController extends Controller {
    
        public function controllerMethod(){
            $departments = $query::module(1)->where([
                ['module', '=', $this->departmentsModuleId],
            ])
            ->whereNull('parent')
            ->with(['taxChildren'])
            ->get();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-30
      • 2018-08-20
      • 2017-04-02
      • 2020-09-07
      • 2022-07-07
      • 1970-01-01
      • 1970-01-01
      • 2019-05-22
      相关资源
      最近更新 更多