Laravel laratables如何在封装中使用id

huangapple go评论93阅读模式
英文:

Laravel laratables how to use id in enclosure

问题

我正在使用Laratables包。我有一个函数用于为数据表格获取数据,但我只需要按用户ID查询。

  1. public function data($id)
  2. {
  3. return Laratables::recordsOf(User::class, function($query)
  4. {
  5. return $query->where('manager_id', $id)->where('status', 'Enabled');
  6. });
  7. }

我遇到了一个错误:

未定义变量:id

我不确定如何在这个函数内部使用id变量。

英文:

I'm using the Laratables package. I have a function to being in the data for the datatable but I need to only query for a user by ID.

  1. public function data($id)
  2. {
  3. return Laratables::recordsOf(User::class, function($query)
  4. {
  5. return $query->where('manager_id', $id)->where('status', 'Enabled');
  6. });
  7. }

I get an error:

> Undefined variable: id

I'm not sure how I can use the id variable inside this function.

答案1

得分: 1

如果您使用的是 php < 7.4 版本,则可以像下面这样操作:

  1. public function data($id)
  2. {
  3. return Laratables::recordsOf(User::class, function($query) use ($id)
  4. {
  5. return $query->where('manager_id', $id)->where('status', 'Enabled');
  6. });
  7. }

如果您使用的是 php 7.4 版本,则可以使用短闭包/箭头函数来实现:

  1. public function data($id)
  2. {
  3. return Laratables::recordsOf(User::class, fn($query) =>
  4. $query->where('manager_id', $id)->where('status', 'Enabled')
  5. );
  6. }

要了解更多关于 匿名函数 的信息,请访问这里或者这里

希望能对您有所帮助。

谢谢

英文:

If you are using php < 7.4 then you can do something like below:

  1. public function data($id)
  2. {
  3. return Laratables::recordsOf(User::class, function($query) use ($id)
  4. {
  5. return $query->where('manager_id', $id)->where('status', 'Enabled');
  6. });
  7. }

and if your are using php 7.4 then you can use short closure/arrow function for this.

  1. public function data($id)
  2. {
  3. return Laratables::recordsOf(User::class, fn($query) =>
  4. $query->where('manager_id', $id)->where('status', 'Enabled')
  5. );
  6. }

to read more anonymous function visit this or this

Hope this helps.

Thanks

huangapple
  • 本文由 发表于 2020年1月4日 01:43:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/59583025.html
  • laravel
  • php

如何将MySQL表列作为变量放入 :?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定