pbootcms网站模板|日韩1区2区|织梦模板||网站源码|日韩1区2区|jquery建站特效-html5模板网

如何在 4 個表中使用 Laravel 的 hasManyThrough

How to use Laravel#39;s hasManyThrough across 4 tables(如何在 4 個表中使用 Laravel 的 hasManyThrough)
本文介紹了如何在 4 個表中使用 Laravel 的 hasManyThrough的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

我有 4 個表,其結構和流程如下:

I have 4 tables with a structure and flow like this:

User
Accounts
Contacts
Orders

關系如下:

$user->hasMany('accounts')->hasMany('contacts')->hasMany('orders');

$user->hasMany('accounts')->hasMany('contacts')->hasMany('orders');

/** User Model **/
class User extend Eloquent {
    public function accounts(){
        return $this->hasMany('Accounts');
    }

    public function contacts(){
        return $this->hasManyThrough('Contact', 'Account', 'owner_id');
    }

    //how do I get this?
    public function orders(){

    }
}

/** Account Model */
class Account extends Eloquent {
    public function $user(){
        return $this->belongsTo('User');
    }
    public function contacts(){
        return $this->hasMany('Contact');
    }
}

/** Contact Model **/
class Contact extends Eloquent {
    public function account(){
        return $this->belongsTo('Account');
    }

    public function orders(){
        return $this->hasMany('Order');
    }
}

/** Order Model **/
class Order extends Eloquent {
    public function contact(){
        return $this->belongsTo('contact');
    }
}

經典的 hasManyThrough 是不可能的,因為我們有 4 個表.

A classic hasManyThrough is not possible because we have 4 tables.

如何創建關系以便單個用戶可以訪問它的訂單,而無需鏈接每個模型的方法,例如:

How can I create a relationship so that a single user can have it's orders accessed without method chaining each model, such as:

User::find(8)->orders;

推薦答案

一開始很難確定查詢構建器是如何將事物切分在一起的.我知道我想如何使用原始 SQL 語句格式化查詢,但我想使用 Eloquent 來完成這個特定任務,因為其他定義的關系.

It was quite difficult at first to identify exactly how the query builder slices things together. I knew how I wanted to format the query with a raw SQL statement, but I wanted to use Eloquent for this particular task given the other defined relationships.

我能夠通過重載屬性并手動創建關系來解決這個問題.但是,實際的查詢和 hasMany 也需要手動構建.讓我們來看看我是如何做到這一點的.請記住,我們的目標是通過 2 個 has-Many 關系從用戶那里獲得 Orders.

I was able to resolve this by overloading the attribute and manually creating the relation. However, the actual query and hasMany needs to be built manually as well. Let's take a look at how I achieved this. Remember, the goal is to get Orders off of the user through 2 has-Many relationships.

一是屬性的重載.

public function getOrdersAttribute()
{
    if( ! array_key_exists('orders', $this->relations)) $this->orders();

    return $this->getRelation('orders');
}

上面函數中的想法是捕獲延遲加載的->orders何時被調用.例如$user->orders.這將檢查 orders 方法是否在現有 User 模型relations 數組中.如果不是,那么它會調用我們的 next 函數來填充關系,最后返回我們剛剛創建的關系.

The idea in the above function is to capture when a lazy loaded ->orders is called. such as $user->orders. This checks to see if the orders method is in the relations array for the existing User model. If it's not, then it calls our next function in order to populate the relatioship, and finally returns the relationship we've just created.

這是實際查詢訂單的函數的樣子:

This is what the function that actually queries the Orders looks like:

public function orders()
{
    $orders = Order::join('contacts', 'orders.contact_id', '=', 'contacts.id')
        ->join('accounts', 'contacts.account_id', '=', 'accounts.id')
        ->where('accounts.owner_id', $this->getkey())
        ->get();

    $hasMany = new IlluminateDatabaseEloquentRelationsHasMany(User::query(), $this, 'accounts.owner_id', 'id');

    $hasMany->matchMany(array($this), $orders, 'orders');

    return $this;
}

在上面,我們告訴 Orders 表加入它的聯系人(在這種情況下,這是給定 belongsTo() 所有權的既定路由).然后從聯系人中,我們加入帳戶,然后從帳戶中我們可以通過將我們的 owner_id 列與我們現有的 $user->id 進行匹配來從我們的用戶那里獲得,所以我們不需要再做任何事情了.

In the above, we tell the Orders table to join it's contacts (which is the established route given the ownership of belongsTo() in this scenario). Then from the contacts, we join the accounts, then from the accounts we can get there from our user by matching our owner_id column against our existing $user->id, so we don't need to do anything further.

接下來,我們需要通過從 Eloquent Relationship 構建器實例化 hasMany 的實例來手動創建我們的關系.

Next, we need to manually create our relationship by instantiating an instance of hasMany from the Eloquent Relationship builder.

鑒于 HasMany 方法實際上擴展了 HasOneOrMany 抽象類,我們可以通過將我們的參數直接傳遞給 HasOneOrMany 抽象類來訪問 HasOneOrManycode>HasMany,如下所示:

Given that the HasMany method actually extends the HasOneOrMany abstract class, we can reach the HasOneOrMany abstract class by passing our arguments directly to HasMany, like below:

$hasMany = new IlluminateDatabaseEloquentRelationsHasMany(User::query(), $this, 'accounts.owner_id', 'id');

HasOneOrMany 期望它的構造函數如下:

The HasOneOrMany expects the following to it's constructor:

Builder $query,
Model $parent,
$foreignKey, 
$localKey

因此,對于我們的構建器查詢,我們傳遞了一個我們希望與之建立關系的模型實例,第二個參數是我們模型的實例($this),第三個參數是來自我們的 Current->2nd 模型,最后一個參數是我們當前模型中與 Current->2nd 模型上的外鍵約束相匹配的列.

So for our builder query, we've passed an instance of our model that we wish to establish the relationship with, the 2nd argument being an instance of our Model ($this), the 3rd argument being the foreign key constraint from our Current->2nd model, and finally the last argument being the column to match from our current model against the foreign key constraint on our Current->2nd model.

一旦我們從上面的 HasMany 聲明中創建了 Relation 的實例,我們就需要將關系的結果與它們的許多父項進行匹配.我們使用接受 3 個參數的 matchMany() 方法來做到這一點:

Once we've created our instance of Relation from our HasMany declaration above, we then need to match the results of the relationship to their many parents. We do this with the matchMany() method which accepts 3 arguments:

array $models,
Collection $results,
$relation

因此在這種情況下,模型數組將是我們當前 eloquent 模型(用戶)的數組實例,可以將其包裝在數組中以實現我們的效果.

So in this case, the array of models would be an array instance of our current eloquent model (user) which can be wrapped in an array to achieve our effect.

第二個參數將是我們在 orders() 函數中初始 $orders 查詢的結果.

The 2nd argument would be the result of our intitial $orders query in our orders() function.

最后,第三個參數將是我們希望用來獲取此關系實例的關系 string;這對我們來說是order.

Finally, the 3rd argument will be the relation string that we wish to use to fetch our instance of this relationship; which for us is order.

現在您可以正確使用 Eloquent 或 Lazy Loading 來為我們的用戶獲取訂單.

Now you can correct use either Eloquent or Lazy Loading to fetch our orders for our user.

User::find(8)->orders();

$user->orders;

希望這對面臨類似問題的其他人有所幫助.

Hopefully this is helpful for someone else facing a similar issue.

這篇關于如何在 4 個表中使用 Laravel 的 hasManyThrough的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

Magento products by categories(按類別劃分的 Magento 產品)
Resource interpreted as image but transferred with MIME type text/html - Magento(資源被解釋為圖像但使用 MIME 類型 text/html 傳輸 - Magento)
Is there an event for customer account registration in Magento?(Magento 中是否有客戶帳戶注冊事件?)
Magento addFieldToFilter: Two fields, match as OR, not AND(Magento addFieldToFilter:兩個字段,匹配為 OR,而不是 AND)
quot;Error 404 Not Foundquot; in Magento Admin Login Page(“未找到錯誤 404在 Magento 管理員登錄頁面)
Get Order Increment Id in Magento(在 Magento 中獲取訂單增量 ID)
主站蜘蛛池模板: PTFE接头|聚四氟乙烯螺丝|阀门|薄膜|消解罐|聚四氟乙烯球-嘉兴市方圆氟塑制品有限公司 | 体感VRAR全息沉浸式3D投影多媒体展厅展会游戏互动-万展互动 | 杭州网络公司_百度SEO优化-外贸网络推广_抖音小程序开发-杭州乐软科技有限公司 | 注塑_注塑加工_注塑模具_塑胶模具_注塑加工厂家_深圳环科 | 广东高华家具-公寓床|学生宿舍双层铁床厂家【质保十年】 | 伸缩节_伸缩器_传力接头_伸缩接头_巩义市联通管道厂 | 大连海岛旅游网>>大连旅游,大连海岛游,旅游景点攻略,海岛旅游官网 | 广州各区危化证办理_危险化学品经营许可证代办 | 盐水蒸发器,水洗盐设备,冷凝结晶切片机,转鼓切片机,絮凝剂加药系统-无锡瑞司恩机械有限公司 | 复合肥,化肥厂,复合肥批发,化肥代理,复合肥品牌-红四方 | 车充外壳,车载充电器外壳,车载点烟器外壳,点烟器连接头,旅行充充电器外壳,手机充电器外壳,深圳市华科达塑胶五金有限公司 | 丙烷/液氧/液氮气化器,丙烷/液氧/液氮汽化器-无锡舍勒能源科技有限公司 | 成都LED显示屏丨室内户外全彩led屏厂家方案报价_四川诺显科技 | 软文推广发布平台_新闻稿件自助发布_媒体邀约-澜媒宝 | 电动高尔夫球车|电动观光车|电动巡逻车|电动越野车厂家-绿友机械集团股份有限公司 | 建筑工程资质合作-工程资质加盟分公司-建筑资质加盟 | 环讯传媒,永康网络公司,永康网站建设,永康小程序开发制作,永康网站制作,武义网页设计,金华地区网站SEO优化推广 - 永康市环讯电子商务有限公司 | 潜水搅拌机-双曲面搅拌机-潜水推进器|奥伯尔环保 | 柔软云母板-硬质-水位计云母片组件-首页-武汉长丰云母绝缘材料有限公司 | 陶瓷砂磨机,盘式砂磨机,棒销式砂磨机-无锡市少宏粉体科技有限公司 | 汽车润滑油厂家-机油/润滑油代理-高性能机油-领驰慧润滑科技(河北)有限公司 | 避光流动池-带盖荧光比色皿-生化流动比色皿-宜兴市晶科光学仪器 东莞爱加真空科技有限公司-进口真空镀膜机|真空镀膜设备|Polycold维修厂家 | 德州万泰装饰 - 万泰装饰装修设计软装家居馆 | 东莞螺丝|东莞螺丝厂|东莞不锈钢螺丝|东莞组合螺丝|东莞精密螺丝厂家-东莞利浩五金专业紧固件厂家 | 知网论文检测系统入口_论文查重免费查重_中国知网论文查询_学术不端检测系统 | 浙江宝泉阀门有限公司 | 高楼航空障碍灯厂家哪家好_航空障碍灯厂家_广州北斗星障碍灯有限公司 | 黄石妇科医院_黄石东方女子医院_黄石东方妇产医院怎么样 | atcc网站,sigma试剂价格,肿瘤细胞现货,人结肠癌细胞株购买-南京科佰生物 | 成都顶呱呱信息技术有限公司-贷款_个人贷款_银行贷款在线申请 - 成都贷款公司 | 网优资讯-为循环资源、大宗商品、工业服务提供资讯与行情分析的数据服务平台 | 上海质量认证办理中心| 膜结构车棚|上海膜结构车棚|上海车棚厂家|上海膜结构公司 | 郑州宣传片拍摄-TVC广告片拍摄-微电影短视频制作-河南优柿文化传媒有限公司 | 扫地车厂家-山西洗地机-太原电动扫地车「大同朔州吕梁晋中忻州长治晋城洗地机」山西锦力环保科技有限公司 | RFID电子标签厂家-上海尼太普电子有限公司 | 环保袋,无纺布袋,无纺布打孔袋,保温袋,环保袋定制,环保袋厂家,环雅包装-十七年环保袋定制厂家 | 防堵吹扫装置-防堵风压测量装置-电动操作显示器-兴洲仪器 | 消电检公司,消电检价格,北京消电检报告-北京设施检测公司-亿杰(北京)消防工程有限公司 | DDoS安全防护官网-领先的DDoS安全防护服务商 | 塑料撕碎机_编织袋撕碎机_废纸撕碎机_生活垃圾撕碎机_废铁破碎机_河南鑫世昌机械制造有限公司 |