There are 3 tables. First one is orders:
After example order:
class Order extends Model
{
// Table Name
protected $table = 'orders';
// Primary Key
public $primaryKey = 'id';
// Timestamps
public $timestamps = true;
public function user() {
return $this->belongsTo('App\User');
}
public function orderproduct() {
return $this->hasMany('App\OrderProduct');
}
}
Second one is OrderProduct table:
class OrderProduct extends Model
{
// Table Name
protected $table = 'order_product';
// Primary Key
public $primaryKey = 'id';
// Timestamps
public $timestamps = true;
public function order() {
return $this->belongsTo('App\Order');
}
public function product() {
return $this->hasMany('App\Product');
}
}
Third one is products table:
class Product extends Model
{
// Table Name
protected $table = 'products';
// Primary Key
public $primaryKey = 'id';
// Timestamps
public $timestamps = true;
public function orderproduct() {
return $this->belongsTo('App\OrderProduct');
}
}
I am not sure with the relations.
What I am trying to do is: after user places an order, how do I write the correct eloquent query to display the order user has placed with the product he ordered? I mean I am redirecting user to their orders page after they place an order, right there I want to show their order details.
Edit:
I reach user id with this: auth()->user()->id
Now with using this id i can reach order_date from first table.
Orders id is foreign key (order_id) in orderproduct table.
From second table take quantity and using product_id in second table reach information of product(name,img,price...)
So in the end i would like to display
Order ID Ordered Products Name Ordered Products Img Quantity of product ordered Order Date Paid Money(Quantity x price)
Related
I'm learning Laravel right now and I'm stumped on how to get an array of records from one table that belong to a record on another table based on a key.
I have two tables:
titles
-------------------
id | title_name | created_at | updated_at
posts
-------------------
id | titles_id | content
I have the route /{title_name} being controlled by the read() method on my PagesController.php
public function read($title){
$title_name = $title;
$title_id = Title::find($title)->id;
$posts = Title::find($title)->posts;
return view('pages/read')->with([
'title_name' => $title_name,
'title_id' => $title_id,
'posts' => $posts
]);
}
But this doesn't seem to output anything. I have my models setup like this:
Title.php
class Title extends Model
{
// Table Name
protected $table = "titles";
// Primary Key
protected $primaryKey = "title";
// Timestamps
public $timestamps = "true";
// Custom primaryKey
public $incrementing = false;
//relationship
public function posts(){
return $this->hasMany('App\Post', 'titles_id')->orderBy('created_at', 'desc');
}
}
Post.php
class Post extends Model
{
// Table Name
protected $table = "posts";
// Primary Key
protected $primaryKey = "id";
// Timestamps
public $timestamps = "true";
//relationship
public function titles(){
return $this->belongsTo('App\Title');
}
}
I think the problem is that when I do Title::find($title)->post, laravel is trying to find posts where the titles_id = title_name, because I set title_name as the primaryKey, but I need it to be looking for the id column in the Titles table, and not the name...
Alright I will give you an example where I explain everything you do wrong.
Tables:
titles
-------------------
id | title_name | created_at | updated_at
posts
-------------------
id | title_id | content
Not titles_id but title_id, eloquent likes this more.
Your controller:
public function read($titleName){
// The first function argument is the name of the title,
// not the title model.
// Also don't use snake_case in laravel(Except helpers) but camelCase.
// We are not going to use find, you might have set the name as
// primary key, but the id column still exists.
// firstOrFail() means get the first result, if there isn't, throw
// a model not found exception(404).
$title = Title::where('name', $titleName)->firstOrFail();
return view('pages/read')->with([
// You could just do 'title' => $title, and do the rest in the view.
'title_name' => $title->name,
'title_id' => $title->id,
'posts' => $title->posts
]);
}
Title model:
class Title extends Model
{
// $table not needed, laravel knows this(Yes pure magic).
// No, we don't want name as primary key.
// Timestamps is true by default, so we don't need it.
public function posts(){
return $this->hasMany(\App\Post::class)->orderBy('created_at', 'desc');
}
}
Post model:
class Post extends Model
{
// This function should be called title, not titles.
public function title(){
return $this->belongsTo(App\Title::class);
}
}
I use Laravel 5.3.
I have 2 tables and 2 models (ad and category) :
Model ad :
----------------
class Ad extends Model
{
protected $table = 'ads';
protected $primaryKey = 'ad_id';
public function category()
{
return $this->belongsTo(Category::class, 'cat_id', 'cat_id');
}
}
And
Model category :
-----------------
class Category extends Model
{
protected $table = 'categories';
protected $primaryKey = 'cat_id';
public function ads()
{
return $this->hasMany(Ad::class);
}
}
And my DB structure is :
ads:
ad_id -
ad_name
ad_status
cat_id
categoriess:
cat_id -
cat_name
I really don't know why, but I can't get the relation between using this (in my repository):
return $this->model
->select('ad_id', 'ad_name')
->where('ad_status', '=', 1)
->with('category');
The query is fine, I got ad information, but the relation is empty. I checked, the cat_id exists in both tables.
Did I miss something ?
You need to add cat_id key to select() to make it work:
return $this->model
->select('ad_id', 'ad_name', 'cat_id')
->where('ad_status', 1)
->with('category')
->get();
If you'll not add this key, relation will be always null. Also, use get() to get the data.
I have users table which has a hasOne relationship with vendordetails table.
class User extends Authenticatable
{
public function vendor_details() {
return $this->hasOne('App\Vendordetail');
}
}
On the other side vendordetails table contains country_id, state_id and city_id and has relationship of belongsTo with Country, State and City model.
Vendordetail.php model is:-
class Vendordetail extends Model
{
public $timestamps = false;
public function this_country(){
return $this->belongsTo('App\Country', 'country_id');
}
public function this_state(){
return $this->belongsTo('App\Country', 'state_id');
}
public function this_city(){
return $this->belongsTo('App\Country', 'city_id');
}
}
How can i fetch records of country, state and city if i query on users table.
$user = User::with('vendor_details')->first();
In this query it only finds the result of vendordetails table, i also wants country, state and city.
Thanks
To access nested relationship
$user = User::with(['vendor_details.this_state','vendor_details.this_country','vendor_details.this_city'])->first();
I have 3 sample models
customer
id
order
id
customer_id
deliver_address_id
customer_address
id
customer_id
street
country
A customer can save many addresses on his profile but he can only choose one address per order.
I would like to get all customer orders including the address in one query using laravel 5 eloquent. I'm new in laravel so having difficulty to query complex relationship tables.
class Customer extends Model {
$table = 'customers';
function addresses(){
return $this->hasMany(Address::class, 'customer_id');
}
function orders(){
return $this->hasMany(Order::class, 'customer_id');
}
}
class Order extends Model {
$table = 'orders';
function address(){
return $this->belongsTo(Address::class, 'address_id');
}
function customer() {
return $this->belongsTo(Customer::class, 'customer_id');
}
}
class Address extends Model{
$table = 'customer_addresses';
function customer(){
return $this->belongsTo(Customer::class, 'customer_id');
}
}
TABLES :
1 customers
id
2 orders
id
customer_id
address_id
3 customer_addresses
id
customer_id
street
country
I want to make a relation with 3 table using ORM but cant. My tables
User table
id | userame | name |
1 Ellie Elen
2 Pol Paul
record table
id | user_id| item_id| hour|
1 2 1 3
2 2 2 5
Item table table
id | title
1 item 1
2 item 2
I am using this logic but not work properly
class User Extends Eloquent {
public function record()
{
return $this->hasMany('VolunteerRecord');
}
}
class VolunteerRecord Extends Eloquent {
function item() {
return $this->hasMany('VolunteerItem');
}
}
I cant understand how to do it?
It seems like you want a Many-To-Many relationship between Users and Items but you also want to track hours on the pivot table. So first, you'll define the many-to-many relationships using belongsToMany(), and you'll tell Laravel that you have extra data on your pivot table with the withPivot() function. Your classes will look like this:
class User extends Eloquent {
protected $table = 'users';
public function items() {
return $this->belongsToMany('Item', 'records')->withPivot('hour');
}
}
class Item extends Eloquent {
protected $table = 'items';
public function users() {
return $this->belongsToMany('User', 'records')->withPivot('hour');
}
}
Then, to access the hour field you would do this:
$user = User::first(); // First User
$item = $user->items()->first(); // User's first Item
$hour = $item->pivot->hour; // The 'hour' on the User-Item relationship
Also, your current column naming scheme is correct for Laravel so don't feel like you need to change it. If you change your column names, then you'll need to define them in the belongsToMany() method like this:
$this->belongsToMany('ModelName', 'pivot_table', 'foreign_key', 'other_key');
// For example, in Items::users() you would have this:
$this->belongsToMany('User', 'records', 'users_id', 'items_id');
Finally, I'm assuming that your tables are named users, items, and records. If they are not, then just replace all instances of users, items, and records with your actual table names.
Based on your table names, I'd suggest the following, first of all, change your record table as follows:
id | users_id| items_id| hour|
1 2 1 3
2 2 2 5
And these are the classes for your models:
class Users extends Eloquent
{
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
public function records()
{
return $this->hasMany('Records');
}
}
class Records extends Eloquent
{
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'records';
public function record()
{
return $this->hasOne('Users');
}
public function item()
{
return $this->hasOne('Items');
}
}
class Items extends Eloquent
{
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'items';
public function records()
{
return $this->hasMany('Records');
}
}
These contain the relations for your models.
If you were to select a few records, for each record you can get the user and the item. If you were to select an item, and all records for that item. You can also get the user for each record.
In User Model
public function images()
{
return $this->belongsToMany('Item')->withPivot('hour');
}
In user controller
public function view($username)
{
$user = User::where('name',$username)->firstOrFail();
return View::make('view')->with('user',$user);
}
In view
#foreach ($users->items as $item)
name: {{$image->title}}<br>
hour: {{$image->pivot->hour}}<br>
#endforeach