laravel orm 多態關聯如何使用自訂字段
曾经蜡笔没有小新
曾经蜡笔没有小新 2017-05-16 16:47:59
0
1
599

有以下三張表

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.以後注意一下排版。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板