【问题标题】:How can I pass a parameter from the controller index function to the model's functions? LARAVEL如何将参数从控制器索引函数传递给模型的函数?拉拉维尔
【发布时间】:2021-06-10 23:01:35
【问题描述】:

//--------------------------------------------// //下面是控制器索引功能代码 // //-------------------------------------------//

public function index($from, $to,$id)
    {
         $data=Attendance::where('attendance_date','>=',$from)
         ->where('attendance_date','<=',$to)
         ->with('userAttendance')//--> **I need to pass the $id to this function in the model**
         ->with('admin')
        ->get()

//------------------------------------------------// //下面是模型代码 // //------------------------------------------------//

class Attendance extends Model
{
    protected $table = "attendances";
    protected $fillable=[
        'attendance_date',
        'admin_id',
    ];
                                       //---> **i need the $id passed to here**
    public function userAttendance()
    {
       return $this->belongsToMany('App\User', 'user_attendances','attendance_id','user_id')
       ->withPivot(
        'present_absent',
        'excuse',
        'attendance_key_amount',
        'verified_date',
        'comment',
       );
    }
}

【问题讨论】:

  • 你想传递什么,为什么?请分享更多逻辑。
  • 我在控制器中接收到来自我的路由的几个变量,其中一个名为 $id,所以我需要将这个 $id 传递给名为 userAttendance 的函数model 我正在使用 Attendance。我已经使用 eloquent -&gt;with(userAttendance) 在控制器索引中调用了这个函数,那么如何将 控制器 中的 $id 变量传递给模型中的这个 函数

标签: php laravel api eloquent backend


【解决方案1】:

试试这个

控制器:

 public function index()
    {
        $id = 50;
        Product::getId(50);
    }

型号:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    public static function getId($id){
        dd($id);
    }
}

【讨论】:

  • 非常感谢你的工作,模型中的功能必须是静态的,如你所说。
猜你喜欢
  • 1970-01-01
  • 2020-06-19
  • 1970-01-01
  • 2017-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-27
  • 2018-05-11
相关资源
最近更新 更多