dplht39359 2013-07-18 17:15
浏览 31
已采纳

雄辩有多重关系

I'm new to Laravel and ORMs in general, so this is probably a very basic concept that I'm missing. I have three tables that I'm trying to define a relation with using Laravel 4's Eloquent ORM. Here's the slimmed-down table definitions:

stores
id (PK)
name

postal_codes
id (PK)
postal_code
city
state
country

locations
id (PK)
store_id (FK => stores.id)
postal_code_id (FK => postal_codes.id)
*additional location-specific fields such as address, phone #, etc

The stores table has a one to many relationship with the locations table, so I can use $this->hasMany("Location") in the Stores model, and $this->belongsTo("Store") in the Location model.

My question is, how do I define the relation between locations and postal_codes in their respective models? The locations table has a many-to-one relationship with the postal_codes table. Ideally I want to be able to do something like this: $store->locations()->first()->city. Is this possible?

  • 写回答

3条回答 默认 最新

  • douqiangchuai7674 2013-07-18 20:32
    关注

    Aren't you looking for something like:

    class Locations 
    {
        public function city()
        {
            return $this->belongsTo('PostalCode');
        }
    }
    

    So now you can call $store->locations()->first()->city. This will return a PostalCode model, if you want to return just the city:

    public function getCity()
    {
        return $this->city()->city;
    }
    

    And then you call $store->locations()->first()->getCity().

    You could go further and create a __get() magic method so it calls everything dynamically.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度