代码之家  ›  专栏  ›  技术社区  ›  nowox

如何加入雄辩?

  •  0
  • nowox  · 技术社区  · 6 年前

    我想做自动连接分组时,选择从一个雄辩的模型在拉威尔。

    假设我有这些表:

    humans        pets 
    ------        ----
    int id        int id
    varchar name  varchar name
                  varchar category  
                  int owner_id 
    

    填充以下值:

    humans        pets
    ------        ----
    1 Bob         1 Lucy Dog 1
    2 Alice       2 Sadie Dog 1 
    3 Eve         3 Buster Cat 2
                  4 Sam Fish 2
    

    class Human extends Eloquent {
    }
    
    class Pet extends Eloquent {
    }   
    

    function wish() {
       return Human::all()->magic()->toJson();
    }
    

    magic() 我应该加入吗?

    [
      {
        "id": 1,
        "name": "Bob",
        "pets": [
          {"id": 1, "name": "Lucy", "category": "Dog"},
          {"id": 2, "name": "Sadie", "category": "Dog"}
        ]
      },
      {
        "id": 1,
        "name": "Alice",
        "pets": [
          {"id": 3, "name": "Buster", "category": "Cat"},
          {"id": 4, "name": "Sam", "category": "Fish"}
        ]
      },
      {
        "id": 1,
        "name": "Eve",
        "pets": []
      }
    ]
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   nowox    6 年前

    您的魔术分两步完成:

    class Human extends Eloquent {
        public function pets() 
        {
            return $this->hasMany('Pet');
        }
    }
    

    还有你的问题

    function wish() {
       return Human::with('pets')->all()->toJson();
    }
    

    您还可以包括 with

    class Human extends Eloquent {
        protected $with = ['pets'];
    
        public function pets() 
        {
            return $this->hasMany('Pet');
        }
    }
    

    有关这方面的文档可从以下位置获得:

    https://laravel.com/docs/5.7/eloquent-relationships