dongshi4078 2013-12-27 09:51
浏览 9

Laravel通过(级别/树)关系雄辩一对一

Hi I'm new to laravel (eloquent). I'm trying to make one to one through (level/tree) relationship using eloquent ORM. I have product_category table that have id and parent_id.

This is my product_category table

|-----|--------|-----------|
| id  |  name  | parent_id |
|-----|--------|-----------|
|  1  |  book  |     0     |
|  2  |notebook|     1     |

This is my product table

|----|----------------|-------------|
| id | name           | category_id |
|----|----------------|-------------|
|  1 | super notebook |      2      |

I want to be able to pull parent category information from subcategory_id info in product alone. Is this possible?

When using SQL, this is the query (assume category_id is 2)

SELECT * FROM  `product_category` WHERE  `id` = (SELECT  `parent_id`  FROM `product_category`  WHERE  `id` =  '2' )

Update:

This is my current implementation

<?php

    class Product extends Eloquent {

        public function subcategory()
        {
            return $this->hasOne('ProductCategory');
        }

        public function category()
        {
            // This should get the parent info of the subcategory
            return ProductCategory::find($this->subcategory->parent_id);
        }

    }
  • 写回答

1条回答 默认 最新

  • dpe77294 2013-12-29 11:02
    关注

    A basic 1-2-1 relationship is done like this:

    Product model

    class Product extends Eloquent {
    
        public function category()
        {
            return $this->hasOne('Category');
        }
    
    }
    

    Category model

    class Category extends Eloquent {
    
        public function product()
        {
            return $this->belongsTo('Product');
        }
    
    }
    

    Now you can query for data like this:

    Product::find(1)->category;
    

    Generated SQL:

    select * from products where id = 1

    select * from categories where product_id = 1

    Basically you should rename your columns to match laravels defaults, else set the keys like $this->hasOne('Category', 'foreign_key');

    See docs also

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题