duanhuang1699 2013-08-16 20: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 20: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.

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

报告相同问题?

悬赏问题

  • ¥20 易康econgnition精度验证
  • ¥15 线程问题判断多次进入
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致