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 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大