我正在尝试获取关系数据,但Trying to get property 'district_name' of non-object
出现错误。我只是在学习laravel。
这是我的模型:
自由学校
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class LibSchool extends Model
{
function getAllSchool()
{
return LibSchool::all();
}
public function district()
{
return $this->belongsTo('App\LibDistrict');
}
}
自由区
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\LibSchool;
class LibDistrict extends Model
{
public function schools()
{
return $this->hasMany('App\LibSchool');
}
}
表
控制器
class SchoolController extends Controller
{
public function index()
{
$q = Input::get('q');
if ($q != "") {
$schools = LibSchool::where('school_name', 'LIKE', '%' . $q . '%')
->with('district')
->orWhere('school_id', 'LIKE', '%' . $q . '%')
->orWhere('address', 'LIKE', '%' . $q . '%')
->orWhere('school_head', 'LIKE', '%' . $q . '%')
->orWhere('level', 'LIKE', '%' . $q . '%')
->orderBy('school_name', 'asc')
->paginate(15)->appends('q', $q);
} else {
$schools = LibSchool::with('district')
->orderBy('school_name', 'asc')
->paginate(15);
}
return view('schools.index')->with('data', ['schools' => $schools, 'q' => $q]);
}
}
看法
<table class="table table-hover table-bordered table-striped">
<tr>
<th>School ID</th>
<th>School NAME</th>
<th>Address</th>
<th>School Head</th>
<th>Level</th>
<th>Division</th>
<th>District</th>
</tr>
@if($data['schools']->total() > 0)
@foreach($data['schools'] as $school)
<tr>
<td>{{$school->school_id}}</td>
<td>{{$school->school_name}}</td>
<td>{{$school->address}}</td>
<td>{{$school->school_head}}</td>
<td>{{$school->level}}</td>
<td>{{$school->district->district_name}}</td>
</tr>
@endforeach
@else
<td colspan="7" class="text-danger">No records</td>
@endif
</table>
{{$data['schools']->links()}}
您给定代码中的问题是您使用了
public function district()
{
return $this->belongsTo('App\LibDistrict');
}
假设您libdistrict_id
在district
表中有外键。但是看看你的表,你似乎已经将它分配为lib_district_id
. 所以,现在你必须明确地输入正确的列名,如下所示:
public function district()
{
return $this->belongsTo('App\LibDistrict', 'lib_district_id', 'id');
}
注意:最好使用 laravel 提供的命名约定。这样我们的代码就可以少得多而且干净。
希望这可以帮助!!玩得开心编码!!:)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句