douyin2435 2013-12-10 21:52
浏览 37
已采纳

Laravel 4 save hasMany return在非对象上调用成员函数save()

I am unable to locate the problem in the following example, I have been looking at the http://laravel.com/docs/eloquent#inserting-related-models but for some reason which I am unable to locate, it's not working.

Models:

class Article extends Eloquent {
  public function category()
  {
    $this->belongsTo('Category');
  }
}

class Category extends Eloquent {

  public function articles()
  {
    $this->hasMany('Article');
  }
}

DB schema:

Articles has a column called category_id which is an integer, and both Articles and Categories have increments on ID column.

Unit test which is currently failing:

  public function testCreateArticleWithCategory()
  {
    $category = new Category();
    $category->name = 'Kitties';

    $this->assertTrue($category->save());

    $cid = $category->id;

    $category = Category::find($cid);

    $article = new Article();
    $article->title = 'Hello Kitty';

    $article = $category->articles()->save($article);

    $this->assertEquals('Kitties', $article->category->name);
  }

The test is failing with the following message:

Starting test 'ArticleTest::testCreateArticleWithCategory'. PHP Fatal error: Call to a member function save() on a non-object in /Users/kristiannissen/Documents/php/sacrebleu/app/tests/ArticleTest.php on line 30

And line 30 is

$article = $category->articles()->save($article);
  • 写回答

2条回答 默认 最新

  • douguazhi5966 2013-12-11 00:11
    关注

    By your question, I am assuming that $this->assertTrue($category->save()); is passing the test?

    Could you show us your schema?

    Also, In your models, shouldn't you do return $this->belongsTo('Category'); and return $this->hasMany('Article');?

    Shouldnt your models be as follows:

    class Article extends Eloquent {
      public function category()
      {
        return $this->belongsTo('Category');
      }
    }
    
    class Category extends Eloquent {
    
      public function articles()
      {
        return $this->hasMany('Article');
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭