【问题标题】:How to use Eloquent relationships with Yajra Datatables?如何在 Yajra Datatables 中使用 Eloquent 关系?
【发布时间】:2020-05-31 23:53:58
【问题描述】:

我正在尝试使用雄辩的关系来显示患者的姓名,而不是患者 ID 外键。相反,它只显示患者 ID,就好像它没有看到关系一样。

我的控制器功能是:

   public function getActions(){
    $data = Action::all();
    return DataTables::of($data)
   ->addColumn('name',function(Action $action){
       return empty ($action->patient->first_name) ? $action->patient_id : $action->patient->first_name;
        //return DB::raw("SELECT * FROM 'patients' WHERE 'patients_id' = ?", $action->patient_id);
    })
    ->make(true);
} 

我在视图中的js函数是:

    <script type="text/javascript">
        $(document).ready(function (){
          $('#actionTable').DataTable({
              processing: true,
              serverSide: true,
              ajax:'{!! route('get.actions')!!}',
              columns:[
                 {data:'action_id', name:'action_id'},
                 {data:'name', name:'name'},
                 {data:'action_status_id', name:'action_status_id'},
                 {data:'is_complete', name:'is_complete'},
              ]
          });
        })
     </script>

我的动作类是:

    class Action extends Model
    {
        protected $table ="actions";

        protected $fillable=[
           'user_id', 'patient_id', 'option_id', 'action_status_id', 'is_complete', 'due_date',
        ];

        protected $primary_key = "action_id";

        public $incrementing = false;

        public function patients(){
              return $this->belongsTo('App\Patient','patient_id','action_id');
        }
   }

我的患者班级是:

     class Patient extends Model
     {
        protected $table ="patients";

        protected $fillable=[
            'first_name', 'last_name', 'email', 'phone', 'dob', 'gender_id', 'is_active',
        ];

        protected $primary_key = 'patient_id';

        public $incrementing = false;

        public function actions(){
            return $this->hasMany('App\Action','action_id','patient_id');
        }
    }

【问题讨论】:

    标签: laravel eloquent datatables yajra-datatable


    【解决方案1】:

    问题是您已将 Action 模型中的关系函数命名为“患者”。而你在打电话

    $action-&gt;patient-&gt;first_name

    我建议将动作模型中的关系函数重命名为

    public function patient()

    这更有意义。

    请参阅文档以获取更多说明One to One Relationships

    【讨论】:

    • 进行了更改,现在收到错误未定义列:列患者.action_id 不存在。有什么想法吗?
    • 我实际上意识到我在关系函数中切换了外键和主键参数的顺序。谢谢!!
    • 去掉患者所属关系中传入的两个可选参数(patient_id, action_id)。 Eloquent 根据模型名称确定关系的外键。因此,在您的情况下,它将自动假定您的操作表中的外键。
    猜你喜欢
    • 1970-01-01
    • 2021-06-20
    • 1970-01-01
    • 2019-10-25
    • 1970-01-01
    • 2022-10-09
    • 2016-03-07
    • 2016-10-05
    • 2016-09-05
    相关资源
    最近更新 更多