There are three tables as follows
business:
id | owner_code | owner_type |
---|---|---|
1 | WSWJDIXSWS | company |
2 | ADSOOEKL23 | personal |
company:
id | code | name |
---|---|---|
1 | WSWJDIXSWS | ibm |
2 | SDFSDFSDFS | h3c |
presonal:
id | code | name |
---|---|---|
1 | ADSOOEKL23 | jack |
2 | SDFSDFSDFS | brown |
Corresponding model
Model Company:
class Company extends Model
{
public function business() {
return $this->morphMany('App\Models\Business', 'owner');
}
}
Model Personal:
class Personal extends Model
{
public function business() {
return $this->morphMany('App\Models\Business', 'owner');
}
}
Model Business:
class Business extends Model
{
public function owner(){
//return $this->morphTo();
return $this->morphTo('owner', 'owner_type', 'owner_code');
}
}
IndexController:
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'));
}
}
view: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>
The results after execution are all unfind!
Use debuger component
The executed statement is as follows:
select * from `businesses`
select * from `companies` where `companies`.`id` in ('')
select * from `personals` where `personals`.`id` in ('')
Laravel's documents all use something similar, owner_type owner_id, but there is no description of how to define fields by yourself
It took me a long time, please explain, I would be grateful
Read more documentation, practice more and use smart IDE.
morphMany
There are 5 parameters.