【问题标题】:Laravel eloquent relationship does not retrieving resultsLaravel 雄辩的关系不检索结果
【发布时间】:2018-06-23 15:55:14
【问题描述】:

我正在尝试用 laravel(5.6) 雄辩地建立表关系。而且我无法从模型中检索关系表结果。下面我提到了关系。

关系:项目有一个类别

这是我的物品模型

class InventoryItems extends Model
{
    /**
     * table row delete
     */
    use SoftDeletes;

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'inventory_items';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $guarded = ['id'];

    protected $fillable = ['name','type_id','category_id','sub_category_id','description','cost_price','sale_price','image_path','image','store_id','status'];


    public function category()
    {
        return $this->belongsTo('App\ItemCategories', 'id', 'category_id');
    }
}

这是我的分类模型

class ItemCategories extends Model
{
    /**
     * table row delete
     */
    use SoftDeletes;

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'item_categories';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $guarded = ['id'];

    protected $fillable = ['name'];
}

这是我的控制器

 public function index(Request $request)
    {
        $items = InventoryItems::all();

        dd($items);

    }

这是结果

Collection {#722 ▼
  #items: array:2 [▼
    0 => InventoryItems {#719 ▼
      #table: "inventory_items"
      #guarded: array:1 [▶]
      #fillable: array:11 [▼
        0 => "name"
        1 => "type_id"
        2 => "category_id"
        3 => "sub_category_id"
        4 => "description"
        5 => "cost_price"
        6 => "sale_price"
        7 => "image_path"
        8 => "image"
        9 => "store_id"
        10 => "status"
      ]
      #connection: "mysql"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:15 [▼
        "id" => 1
        "name" => "Dell Keyboard"
        "type_id" => 1
        "category_id" => 1
        "sub_category_id" => 1
        "description" => "<p>test key</p>"
        "cost_price" => 100.0
        "sale_price" => 500.0
        "image_path" => null
        "image" => null
        "store_id" => 1
        "status" => 1
        "created_at" => "2018-06-02 14:31:32"
        "updated_at" => "2018-06-02 14:31:32"
        "deleted_at" => null
      ]
      #original: array:15 [▶]
      #changes: []
      #casts: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: []
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #forceDeleting: false
    }

我是 eloquent 关系的新手,我参考了 laravel 文档和其他一些教程,但它没有锻炼。一定是个愚蠢的错误想法。

【问题讨论】:

    标签: php mysql laravel-5


    【解决方案1】:

    首先,尝试将with('category') 添加到您的控制器,以便雄辩者知道您正在调用该关系。所以你的控制器应该看起来像

    public function index(Request $request)
        {
            $items = InventoryItems::with('category')->get();
    
            dd($items);
    
        }
    

    第二,我认为关系外键的顺序是错误的应该是

    return $this->belongsTo('YourModel','foreing_key','other_model_key')
    

    所以你们的关系应该是这样的

    return $this->belongsTo('App\ItemCategories', 'category_id', 'id');
    

    【讨论】:

    • 您的解决方案是正确的。但我不得不在我的控制器中使用 get() 而不是 all()。
    【解决方案2】:

    发生了一些事情。

    首先,Laravel 在处理模型关系时使用“急切加载”。

    来自文档。 (https://laravel.com/docs/5.6/eloquent-relationships#eager-loading)

    这意味着在您第一次访问该属性之前不会实际加载关系数据。但是,Eloquent 可以在查询父模型时“预先加载”关系。

    这意味着 Laravel 不会加载你的关系,直到你尝试访问它。

    例如,以下代码将延迟加载类别。

    foreach (InventoryItems::all() as $inventoryItem) {
        dump($inventoryItem->category); // Laravel loads the category here and not before
    }
    

    您还可以在检索模型本身时预先加载关系。

    $items = InventoryItems::all()->load('category'); // Laravel loads the category here.
    
    dd($items);
    

    这里唯一需要注意的是,在预加载时,您应该使用关系函数的名称而不是您检索的模型的名称。

    如果您的类别关系被定义为

    public function itemCategory()
    

    你会使用

    InventoryItems::all()->load('itemCategory');
    

    值得一提的是 ->load() 仅适用于集合而不是构建器。

    对于需要使用的构建器 ->with()

    例如

    InventoryItems::all()->load('category'); // all() has already returned a collection so we have to 'load' additional data
    
    InventoryItems::where('condition','=','something')->with('category')->get(); // This is a builder (until we call get() or first()) so we can ask for the data to be delivered 'with' the category to the collection
    

    【讨论】:

      猜你喜欢
      • 2018-04-13
      • 2021-12-15
      • 2020-09-04
      • 2015-03-14
      • 2018-11-28
      • 2015-01-11
      • 2021-06-03
      • 2020-03-26
      相关资源
      最近更新 更多