与函数不起作用加载有许多关系数据拉拉维尔模型雄辩



>我有两个模型。 此电话型号是一种通用型号,可用于保存和获取用户、客户、员工等的电话值。因此,meta_value用于保存相关模型的 id,meta_key用于确定模型名称关系。

/* Customer Model*/
namespace App;    
use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentSoftDeletes;
class Customer extends Model {
/**
* Get the Phone List.
*/
public function phones(){
return $this->hasMany('AppPhone','meta_value', 'id')
->select('id as phone_id','contact_number as phone','contact_number','country_code','type','dial_code')
->where('meta_key','customer');
}
}
/* Phone Model*/
namespace App;
use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentSoftDeletes;

class Phone extends Model {
/**
* Get the customer that owns the phone.
*/
public function customer(){
return $this->belongsTo('AppCustomer', 'meta_value');
}
}

我无法获取带有客户数据的手机数据。它总是返回

[relations:protected] => Array
(
[phones] => IlluminateDatabaseEloquentCollection Object
(
[items:protected] => Array
(
)
)
)

在我的控制器中,我执行以下代码。

/*This is the case when I want to get the data for a single customer.*/
$customer = Customer::find('448')->with('phones')->get();
print_r($customer); // It will return all customers with no phones value.
$customer = Customer::find('448');
print_r($customer);die; // It will return a single customer whose id is 448 with no phones value.
print_r($customer->phones);die; // I can get the values of phones by this
$customer = Customer::find('448')->with('phones');
print_r($customer);die; // It will crash my postman when i hit this.
/*This is the case when I want to get the data for multiple customers.*/
$customers = Customer::where('id', '>', '447')->with('phones')->get();
print_r($customers);die; // It will return multiple customer with empty phones value.
// However when I iterate through the loop and get phones then I can get the phone value. 
$customers = Customer::where('id', '>', '447')->get();
foreach ($customers as $customer) {
$customer->phones = $customer->phones;
}
print_r($customers);die;

只有迭代有效,但我认为这不是一个好的解决方案。即使我尝试加载功能但不起作用。

您必须选择所需的外键列meta_value

->select('id as phone_id','contact_number as phone','contact_number','country_code',
'type','dial_code','meta_value')

对于单个客户,您不需要急切加载:

$customer = Customer::find(448);
$phones = $customer->phones;

看起来您还应该使用多态关系。

虽然我怀疑选择phone_id作为id可能会影响查询检查关系,但快速调试是从相关函数中删除它:

->select('id as phone_id','contact_number as phone','contact_number','country_code','type','dial_code')
->where('meta_key','customer');

让函数phones简单,

public function phones(){
return $this->hasMany('AppPhone','meta_value', 'id');
}

~更新~

然后,您需要改用load

如果稍后需要进一步检查关系,请传递回调以对其进行筛选:

$customer = Customer::find('448')->load(['phones' => function($query) {
$query->where('meta_key','customer');
}]);

或:

$customer = Customer::with(['phones' => function($query) {
$query->where('meta_key','customer');
}])->find('448');

最初的问题是:

find结果使用withget会为新查询创建模型的另一个实例,因此您只会获得客户的所有记录。可以使用load方法,或者如果要使用with则必须在查询函数的末尾设置筛选器。

为了更好地理解,请查看Laravel关于预先加载的文档

最新更新