Eloquent ORM,当ID位于初始表中,而不是引用表中时


Eloquent ORM, when ID lives within the initial table, not the reference table

当我的模式看起来像这样时,我正试图弄清楚如何使用Eloquent ORM从addresses表中请求记录:

TABLE users {
id
billing_addr_id
shipping_addr_id
}
TABLE addresses {
id
address1
address2
city
state
zip
country
}

正如您所看到的,我想提取billing_addr_idshipping_addr_id的记录,但address表没有对用户的引用,只是因为并非所有地址都连接到users

我希望这是有道理的!

您需要首先定义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);

我忘了地址表上没有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();