[英]Eloquent ORM query — newbie
I am just starting with ORM. 我只是从ORM开始。 I had a question, this is my tabel -- 我有一个问题,这是我的话题-
table a - (aid, aname, atag); 表a-(帮助,名字,标签);
table b - (bid, aid, bname, .. ); 表b-(出价,帮助,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. 所以我尝试了这段代码,对于所有记录,我想要输出- (bname,aname) 。
A model -- 一个模型 -
class A extends Eloquent {
protected $table = 'a';
protected $primaryKey = 'aid';
public function brelation() {
$this->belongsToMany('B','aid');
}
}
B model -- B型-
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. 1)我必须指定外键以确保它们映射。 Because in my actual case they are named differently. 因为在我的实际情况下,它们的名称不同。
2) I am using Laravel 4. 2)我正在使用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. 我仍然无法访问控制器中的aname列,即($ b_item-> aname) 。
A couple of things you should be aware of: 您应该注意以下几点:
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. 如果您有一个自定义主键,则需要将雄辩模型上的$ primaryKey属性设置为数据库中的主键。
You can't mix and match belongsToMany
relationships with anything other than belongsToMany
s. 您不能将belongsToMany
关系与belongsToMany
的其他任何事物混合和匹配。 A belongsToMany
is exclusively for the case where you have two tables that are connected by a pivot table. 当有两个表通过数据透视表连接时, belongsToMany
专门用于此情况。 In your case, B belongsTo
A, and A hasMany
B. 在你的情况下,B belongsTo
A,和A hasMany
B.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.