dsfsfdsf4544 2014-05-31 19:31
浏览 104
已采纳

laravel hasMany没有id

I'm facing a really strange issue in a hasMany relationship, It was not returning me anything so I started digging to try to find something

so now I have this code

    echo $item->id ."<br />";
    var_dump($item->menuMenuCategories()->getParent()->getKey());       echo "<br>";
    var_dump($item->menuMenuCategories()->getParent()->getKeyName());  

echo "
";

    $query = $item->menuMenuCategories()->getBaseQuery()->toSql();
    echo $query ."<br />";

and the result is this:

4 string(1) "4"

string(2) "id"

select * from GS_menu_menu_categories where GS_menu_menu_categories.deleted_at is null and GS_menu_menu_categories.item_id = ?

select * from GS_menu_menu_categories where GS_menu_menu_categories.deleted_at is null and GS_menu_menu_categories.item_id = ?

Can you see the item_id = ? ??

That why it is not returning me anything..

My model has the relationship defined this way:

public function menuMenuCategories(){
    return $this->hasMany('MenuMenuCategory','item_id');
}

Any idea on why it isn't working? I have the hasMany relationship in a thousand places and never had this problem..

Thank you

  • 写回答

1条回答 默认 最新

  • dto52236 2014-05-31 20:59
    关注

    Make sure you have provided everything properly; for example, item_id should be in the related table GS_menu_menu_categories and it should contain an id primary key, or you may specify both if they are different, i.e:

    class Item extends Eloquent {
    
        protected $table = 'items';
    
        public function menuMenuCategories(){
            // if GS_menu_menu_categories has "the_id" instead of "id" as pk
            return $this->hasMany('MenuMenuCategory','item_id', 'the_id');
        }
    }
    

    Use it like:

    $item = Item::with('menuMenuCategories')->find(1); // the item with id 1
    

    Use following to access the related collection of models

    $menuMenuCategories = $item->menuMenuCategories;
    
    $item->menuMenuCategories->first(); // get the first one
    $item->menuMenuCategories->get(1); // get the second one
    $item->menuMenuCategories->get(2); // get the third one
    

    Don't use this:

        $item->menuMenuCategories()
    

    So, for example, in a view (non-blade):

    foreach($item->menuMenuCategories as $category) {
        echo $category->propertyName;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?