Problem: I want to get Customers only if they have already placed an order for the current year. Customers and Orders are on two separate Databases (this can't change). The relationships are all setup and working correctly but when I try the following I keep getting an SQL error as it is trying to search 'orders' on the 'customers' database. Is there anyway to force Laravel to use the correct database in this scenario?
问题:我想要的客户只有当他们已经下了今年的订单。客户和订单位于两个独立的数据库中(这不能改变)。这些关系都是正确设置和工作的,但是当我尝试下面的操作时,我不断地得到一个SQL错误,因为它试图在“客户”数据库上搜索“订单”。在这种情况下,是否有必要强制Laravel使用正确的数据库?
$customers = $customers->whereHas('orders', function($query){
$query->where('academic_year_id', '=', $this->current_academic_year->id);
});
$customers = $customers->orderBy('DFKEY','ASC')->get();
Order Model:
命令模式:
public function customer()
{
return $this->belongsTo('Customer','dfkey');
}
Customer Model:
客户模型:
protected $connection = 'mysql2';
public function orders()
{
return $this->hasMany('Order','dfkey','DFKEY');
}
Thanks in advance!
提前谢谢!
0
Try to write query like this and put your database and tablename as it is->
尝试编写这样的查询,并将您的数据库和表名设置为->
$customers = Schema::connection('your_database_name')::table('respective_table_name')
->where('academic_year_id', '=', $this->current_academic_year->id)
->orderBy('DFKEY','ASC')
->get();
0
Solved this by using a filter:
通过使用过滤器来解决这个问题:
public function index()
{
$customers = new Customer;
// Make sure customers are current parents of students
$customers = $customers->whereHas('students', function($q) {
$q->where('STATUS', '=', 'FULL');
});
//Filter results
if(Input::get('academic_year') == 'ordered'){
$customers = $customers->orderBy('DFKEY','ASC')->get();
$filtered = $customers->filter(function($customer)
{
if ($customer->orders()->where('academic_year_id','=',$this->current_academic_year->id)->first()) {
return true;
}
});
$customers = $filtered;
return View::make('admin.customers.index',compact('customers'));
}
$customers = $customers->orderBy('DFKEY','ASC')->get();
return View::make('admin.customers.index',compact('customers'));
}
本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2014/12/10/aca3e1c3fac9327eaad9e83f52dac2db.html。