在控制器中我有这样的代码:
public function index(Request $request)
{
$course=Student::with('StudentDetail')->get();
$courses=$course->toArray();
echo "<pre>";print_r($courses);exit;
return view('student.student_listing',['result'=>$courses]);
}
通过这个我得到的结果如下:
Array
(
[0] => Array
(
[id] => 1
[name] => Neha
[email] => neha@sob.com
[roll_no] => 101
[created_at] => 2018-05-22 09:20:18
[updated_at] => 2018-05-22 00:00:00
[student_detail] => Array
(
[id] => 1
[student_id] => 1
[phone] => 11691110876
[course] => Java
[city] => Goa
[state] => 1
[created_at] => 2018-05-22 16:48:36
[updated_at] => 2018-05-22 09:20:43
)
)
[1] => Array
(
[id] => 2
[name] => Ankit
[email] => Ankit@sbo.com
[roll_no] => 102
[created_at] => 2018-05-22 09:20:18
[updated_at] => 2018-05-22 00:00:00
[student_detail] => Array
(
[id] => 2
[student_id] => 2
[phone] => 12313311
[course] => Phps
[city] => Delhi
[state] => 2
[created_at] => 2018-05-23 13:28:19
[updated_at] => 2018-05-15 03:15:13
)
)
)
这里我得到一个字段状态,我得到id这个id 与状态表id相关如何从状态获取值 表基于此ID,我希望此结果为降序 有姓名或身份证我怎么能这样做任何人都可以请帮助我相关 这个。
我喜欢的模型:
StudentDetail Model:
<?php
namespace App\Http\Model;
use Illuminate\Database\Eloquent\Model;
use App\Http\Model\Student;
use App\Http\Model\State;
class StudentDetail extends Model
{
public function Student()
{
return $this->belongsTo(Student::class);
}
public function state()
{
return $this->hasOne(State::class);
}
}
Student model:
<?php
namespace App\Http\Model;
use Illuminate\Database\Eloquent\Model;
use App\Http\Model\StudentDetail;
class Student extends Model
{
public function StudentDetail()
{
return $this->hasOne(StudentDetail::class);
}
}
答案 0 :(得分:1)
您可以使用嵌套的with()
public function index(Request $request)
{
$course=Student::with(['StudentDetail' => function($query){
$query->with('state);
}])->get();
$courses=$course->orderBy('studentDetail.state');
echo "<pre>";print_r($courses);exit;
return view('student.student_listing',['result'=>$courses]);
}
或者你可以简单地使用。
public function index(Request $request)
{
$course=Student::with('StudentDetail.state')->get();;
$courses=$course->orderBy('studentDetail.state');;
echo "<pre>";print_r($courses);exit;
return view('student.student_listing',['result'=>$courses]);
}