取得孩子和父母 - Laravel Eloquent

时间:2016-01-15 00:06:22

标签: laravel laravel-5 eloquent

laravel我有以下2个型号; 这是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');
    }
}

这是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');
    }
}

如何检索孩子及其父母,反之亦然(检索父母及其所有孩子)

任何指导意见。

2 个答案:

答案 0 :(得分:2)

  

要在Laravel中查询关系,请使用with($relation)方法   在你想要的模型类上。

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

将父母及其子女归还:

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

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

与父母一起抚养孩子:

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

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

答案 1 :(得分:0)

让我们假设你有 RestaurantClass 模型,如下所示:

class RestaurantClass extends Model
{
    protected $fillable = [
        'ID',
        'NAME',    
    ];

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

您的餐厅模型如下所示:

class Restaurant extends Model
{   
    protected $fillable = [
        'ID',
        'NAME',
        'RestaurantClassId',    
    ];
    /**
     * Get the restaurant class that owns the restaurant.
     */
    public function restaurantClass()
    {
        // Associating RestaurantClass and Restauran through their ids..
        return $this->belongsTo('App\Models\RestaurantClass', 'RestaurantClassId', 'ID');
    }
}

现在,在您的控制器中,您可以通过多种方式使用此关系,例如:

RestaurantController::with('restaurantClass')->findOrFail($id); // This will bring up all the restaurant classes and you can later use it in your view like $data->restaurantClass->NAME ..

或者您可以在控制器的创建/编辑功能中使用它,如下例所示,然后在您的视图中进一步使用它:

$dataSet = array(
            'restaurantClass' => RestaurantClass::lists('NAME', 'ID')
            );

我希望这个解决方案对你有所帮助,并为你提供了一些关于关系如何工作的见解,但是你可以通过相反的方式转变关系,使其在相反的方向工作,如同,RestaurantClass将拥有这个belongsTo方法,你将能够检索控制器内的所有餐厅。干杯,,