我需要在控制器中使用Model函数,但出现上述错误:
假设$ this来自不兼容的上下文,则不应静态调用非静态方法App \ Models \ Employee :: getEmployeeName()
我的模特:
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Employee extends Model
{
protected $table = ‘BLABLA’;
public function getEmployeeName()
{
if ($this->EmployeeName){
return "{$this->EmployeeName}";
}
return null;
}
}
我的控制器:
use Auth;
use DB;
use App\Models\Bookings;
use App\Models\User;
use App\Models\Employee;
use Illuminate\Http\Request;
class BookingsController extends Controller {
public function postBooking(Request $request){
$employee=Employee::getEmployeeName()->get();
dd($employee);
}
}
答案 0 :(得分:1)
getEmployeeName
是Employee对象的方法。必须在Employee的实例上调用它。在您的情况下,您必须在调用该方法之前获取Employee的实例。也许是通过与$request
一起传递的employee_id来实现的。
public function postBooking(Request $request) {
$employee = Employee::findOrFail($request->input('employee_id'));
dd($employee);
}
此外,由于您已经有了Employee对象,因此现在不需要getEmployeeName
。要获得名称,只需要调用属性:
$employee->name
或$employee->EmployeeName
(无论您如何命名)
答案 1 :(得分:0)
尝试一下: 在您的模型中
public static function getEmployeeName()
{
if ($this->EmployeeName){
return "{$this->EmployeeName}";
}
return null;
}
在您的控制器中:
$employee=Employee::getEmployeeName();
但是如果EmployeeName是一个更好的属性,则可以这样做:
public function getEmployeeNameAttribute()
{
if($this->EmployeeName){return $this->EmployeeName;}
}
并在您的控制器中:
$employees= Employee::find(x);
$employees->employee_name ;
$当您的模型同时包含两个解决方案中的记录集时,这才有价值
希望对您有帮助
答案 2 :(得分:0)
这有效
var kitItemGroups = ...
// I only need the KitItemGroups with a BoxName starting with "A"
var result1 = kitItemGroups.Where(group => group.BoxName.StartsWith("A"))
.ToList();
// Or I only want the first three after sorting by group size
var result2 = kitItemGroups.OrderBy(group => group.FuelKitItems.Count())
.Take(3)
.ToList();
答案 3 :(得分:0)
意思是静态定义函数,在public后面加上static,下面是一个例子
喜欢这个
public static function postBooking(Request $request){
$employee=Employee::getEmployeeName()->get();
dd($employee);
}