抓孩子和父母 - Laravel雄辩 [英] Fetch child and parent - Laravel Eloquent

查看:91
本文介绍了抓孩子和父母 - Laravel雄辩的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

laravel 我有以下2个型号;
这是父母

 <?php 

命名空间App \Models;

使用Illuminate\Database\Eloquent\Model;

class RestaurantClass扩展模型
{
/ **
*获取餐厅类的餐厅。
* /
public function restaurants()
{
return $ this-> hasMany('App\Models\Restaurant');
}
}

这是孩子;

 <?php 

命名空间App\Models;

使用Illuminate\Database\Eloquent\Model;

类餐厅扩展模型
{
/ **
*获取拥有餐厅的餐厅类。
* /
public function restaurantClass()
{
return $ this-> belongsTo('App \Models\RestaurantClass');
}
}

如何检索孩子,它是父母和副


$ b


解决方案方法

/ p>

将此应用于您的示例将如下所示:



它的孩子:

  $ restaurantClasses = RestaurantClass :: with('restaurants') - > get(); 

//访问children
foreach($ restaurantClasses as $ restaurantClass){
$ restaurantClass->餐厅;
}

使用父母保护孩子:

  $ restaurants = Restaurant :: with('restaurantClass') - > get(); 

//访问父模型
foreach($ restaurant as $ restaurant){
$ restaurant-> restaurantClass;
}


In laravel I have the below 2 models; This is the parent

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class RestaurantClass extends Model
{
    /**
     * Get the restaurants for the restaurant class.
     */
    public function restaurants()
    {
        return $this->hasMany('App\Models\Restaurant');
    }
}

And this is the child;

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Restaurant extends Model
{    
    /**
     * Get the restaurant class that owns the restaurant.
     */
    public function restaurantClass()
    {
        return $this->belongsTo('App\Models\RestaurantClass');
    }
}

How can I retrieve the child and it's parent and vice versa (retrieve the parent and all its children)

Any guidance appreciated.

解决方案

To query relationships in Laravel, use the with($relation) method on the model class you want.

Applying this to your example would be like :

Retreive the parent with its children :

$restaurantClasses = RestaurantClass::with('restaurants')->get();

// to access "children" 
foreach($restaurantClasses as $restaurantClass) {
  $restaurantClass->restaurants;
}

Retreive the children with their parent :

$restaurants = Restaurant::with('restaurantClass')->get();

// to access "parent" models
foreach($restaurants as $restaurant) {
  $restaurant->restaurantClass;
}

这篇关于抓孩子和父母 - Laravel雄辩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆