0

addresses当我的模式如下所示时,我试图弄清楚如何使用 Eloquent ORM 从表中请求记录:

TABLE users {
id
billing_addr_id
shipping_addr_id
}

TABLE addresses {
id
address1
address2
city
state
zip
country
}

如您所见,我想为billing_addr_idand提取记录shipping_addr_id,但该address表没有对用户的引用,因为并非所有地址都将连接到users

我希望这是有道理的!

4

2 回答 2

1

你需要先定义你的 Eloquent 模型。

你可以做类似的事情(未经测试)......

<?php
//app/models/address.php
class Address extends Eloquent {
  protected $table = "addresses";

  public function users() {
    return $this->belongsTo('users', 'billing_addr_id', 'shipping_addr_id');
  }
}

//app/models/user.php
class User extends Eloquent {
  protected $table = "users";

  public function address($type = "billing") {
      return Address::where("id", ($type == "billing") ? $this->billing_addr_id : $this->shipping_addr_id);
  }
}

// test the model
$user = User::find(123);
$billingAddress = $user->address("billing")->pluck('address1');
$shippingAddress = $user->address("shipping")->pluck('address1');

var_dump($billingAddress, $shippingAddress);
于 2013-06-25T18:29:14.100 回答
0

我忘了你在地址表上没有 user_id ......那我会这样做......

 class User extends Eloquent {
   protected $table = "users";

   public function bill_to(){
     return Address::where('id','=',$this->billing_addr_id)->first();
   }

   public function ship_to(){
    return Address::where('id','=',$this->shipping_addr_id)->first();
   }

 }

然后你调用你的逻辑......

 $user = User::find(2);
 $address = $user->bill_to();
于 2013-06-25T18:40:59.760 回答