Relate between two tables in model Laravel - php

I have a question, How i can relate two table in model function?
I want to relate between table stores and orders but i can't relate them..
can you help me please?
this is my stores table
and this is my orders table
Update
This is my code
public function order()
{
return $this->belongsTo(Order::class,'id','store_id');
}

Related

Eloquent hasOneThrough relation

Currently my database setup looks like this:
Users table (User model):
id,
email
Discounts table (Coupon model)
code
amount
Now, I decided to create a pivot table, where I will store a discount value for a user. One user will have a single discount value. For this, I created PractitionerVoucher model with this table setup:
voucher_id
practitioner_id
Upon creating a Coupon record, I save the coupon_id (voucher_id in this case) and the user_id (practitioner_id in this case) values to PractitionerVoucher table. Now, my question is, how do I get the User record from the Coupon model? For example:
$coupon = Coupon::first();
$coupon->practitioner;
I tried to create hasOneThrough relation on Coupon model, but no luck so far. This is what I tried:
public function practitioner(){
return $this->hasOneThrough(User::class, PractitionerVoucher::class, 'practitioner_id', 'id');
}
Using this relation, I get no query results for the User model. This is how my database records look like:
Coupons table
PractitionerVoucher table:
What am I doing wrong here? Any help is appreciated.
What you are trying to achieve can be easily done by adding a coupon_id column on users table and defining a One-to-Many relationship between User and Coupon model - there's no need for a pivot table.
On User model
public function discount()
{
return $this->belongsTo(Coupon::class, 'coupon_id');
}
On Coupon model
public function users()
{
return $this->hasMany(User::class);
}
Then you can use the relationship
$coupon = Coupon::with('users')->first();
$coupon->users;

combine table rows if user id is same in foreach loop laravel

I have 3 tables
User, Orders, Extra Orders
and I have used the hasMany method to get the data from tables. When data is inserted in the Extra Orders table having the user id and order id. but when two or three order are of same user id then it should club or combine all the extra orders in same card one by one. like https://prnt.sc/panfhi
but in my case, every row is having a different card. like https://prnt.sc/panga8 and my data is extracting as follows https://prnt.sc/panh0n
kindly advice the solution.
I have tried different methods of foreach loops but it's not working
getting the data from tables.
class GeneralController extends Controller {
public function orderReceived() {
$extra_orders = ExtraOrders::with(['user','orders'])->get();
dd($extra_orders->toArray());`enter code here`
}
}
check your relation function order
Order need to be Hasmany Relationship

Laravel 5.4 Relationships between 3 tables

I am new in laravel, I already know how to join tables using the query builder. I just like to learn how to use relationships to avoid repetition of codes and to simplify it. I can join 2 tables, but I can't get the 3rd table.
I like to display employees assigned tasks information from the Tasks table, this table only has the project id that needs to be joined to the Projects table. Other employees can join in existing projects with other employees.
Employee model:
public function tasks()
{
return $this->hasMany('\App\Task', 'project_coder', 'id');
}
Task model:
public function projects()
{
return $this->hasMany('\App\Project', 'id', 'project_id');
}
Projects model:
public function belongsToTasks()
{
return $this->belongsToMany('\App\Task', 'project_id', 'id');
}
I can only get the IDS from Task model. the ID will be use to fetch the project info from project tables. Unfortunately I cant do that part.
Employees controller:
public function show($id)
{
$data = Employees::find($id);
return view('show-employee')->withInfo($data);
}
Is it good practice to use query builder rather than relationships?
UPDATE:
Employees table
{
"id":1,
"name": "Juan"
}
Tasks table
{
"id":1, // autoincrement and will not be use for linking to other tables.
"project_id": 1, //use to connect to project table
"project_coder": 1 // use to connect to employees table
}
Projects table
{
"id":1,
"name": "First Project"
}
To deal with this is best to create pivot table like employee_task
where table will have just two columns task_id and employee_id
then you can define in Task model
public function employees()
{
return $this->belongsToMany('\App\Employee', 'employee_task');
}
and Employee model
public function tasks()
{
return $this->belongsToMany('\App\Task', 'employee_task');
}
now you can see all employee tasks and rest of you relations work just fine
$data = Employees::find($id);
$data->tasks //you get all tasks assigned to this employee
$data->tasks()->first()->projects //you get all your projects for first task
$data->tasks()->first()->employees //all employees assigned to first task with this employee
Also recommend to you to lookup pivot tables, attach(), detach() and sync() functions. you can check it here : https://laravel.com/docs/5.7/eloquent-relationships#updating-many-to-many-relationships
UPDATE:
Ok I understand now what you are trying to do. You already have pivot table. I was little confused with your Project model which is not necessary.
You can remove your Project class if you have it just for this relation
and update your model relations as I wrote above. You don't need project_id and project_coder_id in this relation. Also change the column names to more conventional names like employee_id and task_id as I mentioned or whatever your table names are.
And you can rename employee_task pivot table name to your project table or you can rename it as well.
EDIT
When you use Project model for another data, you need to create 4th table as I mentioned above.
FINAL
drop project_coder column in Tasks table - unecessary column
create pivot table employees_task with employee_id,task_id
create mentioned relations with pivot table
I assume that Project hasMany() tasks and Task only belongsTo() one project. So need to create these relations as well.
Then you can use these relations like this:
$employee = Employee::find($id);
$task = Task::find($id);
$project = Project::find($id);
$employee->tasks //all tasks assigned to employee
$task->employees //all employees assigned to task
$task->project //project info assigned to task
$employee->tasks()->first()->project //project data from first task of employee
$project->tasks()->first()->employees //all employees assigned to first project task

two foreign keys, how to map with laravel eloquent

I have two tables in MySQL, where the first one is called users and the second one is called games. The table structure is as follows.
users
id (primary)
email
password
real_name
games
id (Primary)
user_one_id (foreign)
user_one_score
user_two_id (foreign)
user_two_score
My games table is holding two foreign relations to two users.
My question is how do I make the model relations for this table structure?? - According to the laravel documentation, I should make a function inside the model and bind it with its relations
for instance
public function users()
{
$this->belongsTo('game');
}
however I can't seem to find anything in the documentation telling me how to deal with two foreign keys. like in my table structure above.
I hope you can help me along the way here.
Thank you
A migration:
$table->integer('player1')->unsigned();
$table->foreign('player1')->references('id')->on('users')->onDelete('cascade');
$table->integer('player2')->unsigned();
$table->foreign('player2')->references('id')->on('users')->onDelete('cascade');
And a Model:
public function player1()
{
$this->belongsTo('Game', 'player1');
}
public function player2()
{
$this->belongsTo('Game', 'player2');
}
EDIT
changed 'game' to 'Game' as user deczo suggested.
Unfortunately the way you have this setup is not likely to work in the current context. You may have more luck with the belongsTo method, but again that only supports one relationship.
You could implement a user1() belongsTo, a user2() belongsTo and finally just declare a non eloquent function to return both (something like $users = array($this->user1(), $this->user2())

Using pivot table with Eloquent and Laravel

Here is my problem. I have a table called news and table called categories, also I have a pivot table that connects these two called news_categories.
I am trying to fetch last 10 articles from certain category, but obviously pivot table doesn't have timestapms.
I was reading about hasMany(), belongToMany() but didn't find a good example of how it is done. Any help is appreciated
So far I have done this to News model:
public function categories(){
return $this->has_many_and_belongs_to("Categories")->withPivot('category_id', 'news_id');
}
But I have no idea how to select News based on pivot table value of category_id
You might want to read up on the Laravel 4 Eloquent Documentation a bit...
The relationship function is wrong and you don't need to specify the pivot items. The withTimestamps() function will automatically manage those on the pivot table for you.
public function categories()
{
return $this->belongsToMany('Category')->withTimestamps();
}

Categories