Terdapat tiga jadual seperti berikut
perniagaan:
id | kod_pemilik | jenis_pemilik |
---|---|---|
1 | WSWJDIXSWS | syarikat |
2 | ADSOOEKL23 | peribadi |
syarikat:
id | kod | nama |
---|---|---|
1 | WSWJDIXSWS | ibm |
2 | SDFSDFSDFS | h3c |
presal:
id | kod | nama |
---|---|---|
1 | ADSOOEKL23 | jack |
2 | SDFSDFSDFS | coklat |
Model sepadan
Syarikat Model:
class Company extends Model
{
public function business() {
return $this->morphMany('App\Models\Business', 'owner');
}
}
Peribadi Model:
class Personal extends Model
{
public function business() {
return $this->morphMany('App\Models\Business', 'owner');
}
}
Perniagaan Model:
class Business extends Model
{
public function owner(){
//return $this->morphTo();
return $this->morphTo('owner', 'owner_type', 'owner_code');
}
}
Pengawal Indeks:
class IndexController extends Controller
{
public function index(){
//DB::connection()->enableQueryLog();
//$queries = DB::getQueryLog();
$businesses = Business::get();
$businesses->load('owner');
return view('index')->with(compact('businesses'));
}
}
pandangan:index.blade
<table bgcolor="#7fffd4" width="400">
<tr>
<td colspan="3" bgcolor="#f5f5dc" align="center">BUSINESS</td>
</tr>
<tr>
<td bgcolor="#f0f8ff">ID</td>
<td bgcolor="#f0f8ff">OWNER_TYPE</td>
<td bgcolor="#f0f8ff">NAME</td>
</tr>
@foreach($businesses as $business)
<tr>
<td bgcolor="#f0f8ff">{{$business->id}}</td>
<td bgcolor="#f0f8ff">{{$business->owner_type}}</td>
<td bgcolor="#f0f8ff">{{object_get($business->owner, 'name', 'unfind')}}</td>
</tr>
@endforeach
</table>
Keputusan selepas pelaksanaan semuanya tidak ditemui!
Gunakan komponen penyahpepijat
Pernyataan yang dilaksanakan adalah seperti berikut:
select * from `businesses`
select * from `companies` where `companies`.`id` in ('')
select * from `personals` where `personals`.`id` in ('')
Dokumentasi Laravel menggunakan sesuatu yang serupa, owner_type owner_id, tetapi ia tidak menyebut cara mentakrifkan sendiri medan
Saya sudah lama bergelut, sila jelaskan, saya amat berterima kasih
Baca lebih banyak dokumentasi, berlatih lebih banyak dan gunakan IDE pintar.
morphMany
Terdapat 5 parameter.