duanhuang1699 2013-08-16 12:47
浏览 45
已采纳

雄辩的ORM查询 - 新手

I am just starting with ORM. I had a question, this is my tabel --

table a - (aid, aname, atag);

table b - (bid, aid, bname, .. );

It is One to Many relationship - that is One aid can belong to many bid but one bid can belong to only one aid.

So I was trying out this code, In the out put I want -- (bname,aname) for all the records.

A model --

class A extends Eloquent {
   protected $table = 'a';
   protected $primaryKey = 'aid';
   public function brelation() {
       $this->belongsToMany('B','aid');
   }
}

B model --

class B extends Eloquent {
   protected $table = 'b';
   protected $primaryKey = 'bid';
   public function getANames() {
       $this->hasOne('A','aid');
   }
}

In Controller --

 foreach(B::with('getANames')->get() as $b_item){
      echo $b_item->bname." , ".$b_item->aname;
 }

Couple of points to clarify --

1) I have to specify the foreign key to make sure they map. Because in my actual case they are named differently.

2) I am using Laravel 4.

Can someone show me what I did wrong and how I can get the desired result.

===== Update =====

 class A extends Eloquent {
   protected $table = 'a';
   protected $primaryKey = 'aid';
   public function brelation() {
       $this->belongsTo('B','aid');
   }
 }

I still cannot access the aname column i.e ($b_item->aname) in the controller.

展开全部

  • 写回答

1条回答 默认 最新

  • duanpao4522 2013-08-16 12:57
    关注

    A couple of things you should be aware of:

    1. If you have a custom primary key, you need to set the $primaryKey property on your eloquent models to the primary keys you have in the DB.

    2. You can't mix and match belongsToMany relationships with anything other than belongsToManys. A belongsToMany is exclusively for the case where you have two tables that are connected by a pivot table. In your case, B belongsTo A, and A hasMany B.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?