laravel orm 多态关联如何使用自定义字段
曾经蜡笔没有小新
曾经蜡笔没有小新 2017-05-16 16:47:59
0
1
598

有如下三张表

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, 没写怎么用自己定义字段
折腾半天了,请解,不胜感激

曾经蜡笔没有小新
曾经蜡笔没有小新

全部回复(1)
左手右手慢动作

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

Ps.以后注意一下排版。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板