简体   繁体   中英

Eloquent ORM query — newbie

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 ie ($b_item->aname) in the controller.

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 belongsToMany s. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM