laravel orm 多态关联如何使用自定义字段

有如下三张表

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

对应的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>

执行后结果全是 unfind!

使用 debuger组件
得到执行后的语句如下:

select * from `businesses`
select * from `companies` where `companies`.`id` in ('')
select * from `personals` where `personals`.`id` in ('')

laravel 的文档里都是用类似, owner_type owner_id, 没写怎么用自己定义字段
折腾半天了,请解,不胜感激

阅读 6k
1 个回答

多看文档多实践多用智能IDE。morphMany有5个参数。

clipboard.png

Ps.以后注意一下排版。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏