1

I have this leftJoin in my Laravel project

products = DB::table('products')
->leftJoin('destinations','products.id','=','destinations.product_id')
->get();

Tables: Product: id,name Destinations:id,product_id,destination,quantity,target_person

but i don't knwo how to display leftJoin,(i just want to display name form product and quantity,destination ,target_person from destinations) and i want to add new record This is my form :

 <form action="." method="POST" id="formid">
    {{ csrf_field() }}
       <div class="form-group">
           <label for="first_name">Product name</label>
           <input class="form-control" name="name" >
       </div>
       <div class="form-group">
           <label for="last_name">Quantity</label>
           <input  class="form-control"  name='quantity'>
      </div>
      <div class="form-group">
          <label for="last_name">Destination<label>
          <input  class="form-control"   name='Destination'>
      </div>
      <div class="form-group">
          <label for="last_name">Target Perosn</label>
          <input  class="form-control"   name='target_person'>
     </div>

  <button type="submit" class="btn btn-primary">Submit</button>
</form>

i never do this,please help me this,im beginner in this.

Csabikaaaa
  • 165
  • 13

1 Answers1

4

As you have mentioned, I just want to display name from product and quantity,destination ,target_person from destinations. You have to use table alias like:

products = DB::table('products as t1')
->leftJoin('destinations as t2','t1.id','=','t2.product_id')
->select('t1.name', 't2.quantity', 't2.destination', 't2.target_person')
->get();
Mayank Pandeyz
  • 25,704
  • 4
  • 40
  • 59
  • I get the following error:SQLSTATE[42S22]: Column not found: 1054 Unknown column 'products.id' in 'on clause' – Csabikaaaa Sep 22 '17 at 09:42
  • Check the updated answer, instead of table name use `alias` in on clause, I forget to update that part – Mayank Pandeyz Sep 22 '17 at 09:45
  • Worked,and how can i add new record with the same leftJoin? i try to read laravel documentaion,but im beginner with laravel – Csabikaaaa Sep 22 '17 at 09:46
  • Run two different query, first one for `products` table, get the `inserted id` and then run another query for `destinations` table with the product `inserted id` – Mayank Pandeyz Sep 22 '17 at 09:50
  • public function index(){ $products = DB::table('products as t1') ->leftJoin('destinations as t2','t1.id','=','t2.product_id') ->select('t1.name', 't2.quantity', 't2.destination', 't2.target_person') ->get(); return view('welcome' , compact('products')); } this s my index method,iwant to display this records,but it doesn't work – Csabikaaaa Sep 22 '17 at 10:03
  • Just only show name ,but i want to three more So when i pass this data to the view and try to foreach them,only show name – Csabikaaaa Sep 22 '17 at 10:06