大家好,我是 PhP 和 Laravel 的新手。我想在 laravel 中使用连接查询并编写下面的代码,但它给了我一个错误。
$data = DB::table('employees')
->join('contact_details', 'employees.id', '=','contact_details.employee_id')
->join('education', 'employees.id', '=', 'education.employee_id')
->join('addresses', 'employees.id', '=', 'addresses.employee_id')
->select('employees.first_name','employees.id','employees.gender','education.id','education.school','education.subject','addresses.village')
->where('employees.id', '=',$id)
->get();
return "$data";
,错误是
ErrorException in ProfileController.php line 66:
Array to string conversion
in ProfileController.php line 66
at HandleExceptions->handleError('8', 'Array to string conversion', 'E:\xampp\htdocs\djiafg\app\Http\Controllers\ProfileController.php', '66', array('id' => '72', 'data' => array())) in ProfileController.php line 66
at ProfileController->view('72')
at call_user_func_array(array(object(ProfileController), 'view'), array('id' => '72')) in Controller.php line 80
at Controller->callAction('view', array('id' => '72')) in ControllerDispatcher.php line 146
at ControllerDispatcher->call(object(ProfileController), object(Route), 'view') in ControllerDispatcher.php line 94
at ControllerDispatcher->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 52
at Pipeline->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
答案 0 :(得分:3)
Laravel有一个特殊的连接函数,称为模型。
Laravel附带的Eloquent ORM提供了一个漂亮,简单的ActiveRecord实现,用于处理数据库。每个数据库表都有一个相应的“模型”,用于与该表进行交互。模型允许您查询表中的数据,以及在表中插入新记录。
模型可以有一个或多个。这将从用户表数据返回一行。
将此添加到您的模型中,该模型从您的employees表中获取数据。
public function user() {
return $this->hasOne('app\User', 'id', 'user_id');
}
现在您可以运行转储用户ID。 (您需要一个名为“员工”的模型,它连接到您的表“员工”)
$employees = Employees::get();
dump($employees->user->id);
我希望这有效!
答案 1 :(得分:0)
尝试在选择之前删除空格并按以下方式设置where条件
$data = DB::table('employees')
->join('contact_details', 'employees.id', '=','contact_details.employee_id')
->join('education', 'employees.id', '=', 'education.employee_id')
->join('addresses', 'employees.id', '=', 'addresses.employee_id')
->select('employees.first_name','employees.id','employees.gender','education.id','education.school','education.subject','addresses.village')
->where('employees.id',$id)
->get();
return view ('profile',compact('data'));