Checkout using a hasManyThrough relationship
Need Help Converting raw SQL into Laravel Many to Many
Apologies ... I'm old school. I learned raw sql and have little trouble with it. BUT, we're learning Laravel right ? Can I get this Laravel Many to Many relationship to work - nope. All I get is an empty array.
So here is my SQL, which works fine, gives me all those customers who have a product with an order status of "1". I also provide my attempt to recreate this is Laravel. There are 3 tables: "customer", "product" and the join table is "transactions" . ( guess I could change that to customer_product if needed)
Could some kind person tell me where I am going wrong and why my Laravel code produces an empty array? All this code is trying to do is find just 1 customer / product relationship. I have not even gotten as far finding a customer with a status yet. I just can't see it any more.
Many Thanks ! :o)
SQL
SELECT c.customer_id, c.co_name, t.status, p.name
From customers as c, transactions as t, products as p
WHERE t.status = '1'
AND c.customer_id = t.customer_id
AND p.product_code = t.product_id
Controller:
<?php
use src\Customer;
class OrderController extends BaseController {
public function index()
{
$segment = ucfirst(Request::segment(1));
$pageTitle = ucfirst(Request::segment(0));
$customers = Customer::find(1)->products;
return View::make ('orders/new_orders', ['customers'=>$customers, 'segment'=>$segment, 'pageTitle'=>$pageTitle]);
}
}
Model
<?php
namespace src;
use Eloquent;
class Customer extends Eloquent {
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'customers';
public $timestamps=true;
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = array('password', 'remember_token');
protected $primaryKey = 'customer_id';
public function products() {
return $this->belongsToMany('src\Product', 'transactions', 'customer_id', 'product_id' );
}
}
Please or to participate in this conversation.