Laravel belongsTo not working even with specific FK - php

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.

Related

How to get all the people in table 1 without getting the people who have me as parent_id in table 2?

I'm writing this post because I have a problem with my relationships on Laravel.
Here is the structure I currently have:
1st table:
- id
- name
- ...
2nd table :
- parent_id
- child_id
knowing that parent_id and child_id correspond to the same table. Here is the function that links them
public function relation()
{
return $this->belongsToMany('App\Person', 'person_relations', 'parent_id', 'child_id', 'id', 'id');
}
Currently I would like, for a search system, to get all the people in table 1 without getting the people who have me as parent_id in table 2.
I have added an inverse relation parents() to the People model instead of the relation() method in the question.
Person Model :
public function parents()
{
return $this->belongsToMany('App\Models\Person', 'person_relations', 'child_id', 'parent_id', 'id', 'id');
}
Controller :
public function test()
{
$myId = 1;
$persons = \App\Models\Person::whereDoesntHave('parents')
->orWhereHas('parents', function($qry) use($myId){
$qry->where('person_relations.parent_id', '!=', $myId);
})
->get();
}
This method will return all records which doesn't have a given $myId as their parent id.
Tested and working in Laravel 6.2 and 7.29

Laravel Eloquent fetching and displaying Customer Orders on Page

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)

Relations Laravel 4 with 3 tables using Eloquent

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

Relationship between a hasMany and belongsToMany in Laravel

I have two Models - InternalNotesThread and InternalNotes
class InternalNotesThread extends Model {
public function notes(){
return $this->hasMany('App\InternalNotes', 'thread_id', 'id');
}
}
class InternalNotes extends Model {
public function thread() {
return $this->belongsTo('App\InternalNotesThread');
}
public function users()
{
return $this->belongsToMany('App\User', 'user_notes_tagged', 'internal_notes_id', 'user_id');
}
}
Also, InternalNotes is mapped to User with a relation of belongsToMany.
DB Structure:
internal_notes_thread:
id - int
ticket_id (FK) - int
name - string
internal_notes:
id - int
thread_id (FK) - int
notes - string
user_notes_tagged: (Many to many with internal_notes and User)
internal_notes_id (FK) - int
user_id (FK) - int
For every note, there might be some user tagged in it.
How can I directly relate this relationship with the internal_notes_thread???
I get the data with this:
$data = InternalNotesThread::with('notes')->where('ticket_id', '=', $id)->get()->toArray();
But, in the notes array, I am not able to get the users tagged in that note
How can I get all the data in one go???
You're not eager loading the users, so they don't show up in your ->toArray() array.
Try this:
$data = InternalNotesThread::with('notes.users')
->where('ticket_id', '=', $id)
->get()
->toArray();

How to implement a self referencing (parent_id) model in Eloquent Orm

I have a User table and need to allow for users to have a parent user.
the table would have the fields:
id
parent_id
email
password
How would I define this self referencing relationship in Eloquent ORM?
I had some success like this, using your exact DB table.
User Model:
class User extends Eloquent {
protected $table = 'users';
public $timestamps = false;
public function parent()
{
return $this->belongsTo('User', 'parent_id');
}
public function children()
{
return $this->hasMany('User', 'parent_id');
}
}
and then I could use it in my code like this:
$user = User::find($id);
$parent = $user->parent()->first();
$children = $user->children()->get();
Give that a try and let me know how you get on!
I had a chain of self referencing contracts (a contract can be continued by another contract) and also needed self referencing. Each contract has zero or one previous and also zero or one next contract.
My data table looked like the following:
+------------------+
| contracts |
+------------------+
| id |
| next_contract_id |
+------------------+
To define the inverse of a relationship (previous contract) you have to inverse the related columns, that means setting
* foreign key column on the model table
* associated column on the parent table (which is the same table)
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Contract extends Model {
// The contract this contract followed
function previousContract()
{
// switching id and next_contract_id
return $this->belongsTo('App\Contract', 'id', 'next_contract_id');
}
// The contract that followed this contract
function nextContract()
{
return $this->belongsTo('App\Contract');
// this is the same as
// return $this->belongsTo('App\Contract', 'next_contract_id', 'id');
}
}
See http://laravel.com/docs/5.0/eloquent#one-to-one for further details.

Categories