Laravel 5 Eloquent ORM multi relation - php

I'm totally new in Laravel, and I'm trying to create relations between models. My tables are:
patch
id
title
area
id
location
area_patch
id
patch_id
area_id
user_area_patch
id
area_patch_id
plant_id
plant_date
User model, "patchs" function should execute something like this:
SELECT
p.id, p.title, up.plant_id, up.plant_date
FROM
rsst_farming_patch p
JOIN rsst_farming_area_patch pp,
rsst_farming_user_patch up ON pp.id = up.area_patch_id AND p.id = pp.patch_id WHERE up.user_id = 1
my models:
class User extends Model {
public function patchs() {
//return user patchs
}
}
class Patch extends Model {
public function area() {
//return area that this patch belongs to
}
}
class Area extends Model {
public function patchs() {
//return available patchs
}
}
can some one make an example of this? I would like to study it. I was messing around with User model, belongsToMany and hasManyThrough, but no luck.

You may need to modify your table structure slightly to make this happen.
I see in youruser_area_patch table you are trying to link the user, area, and patches together. That's not typically how I've done it in laravel. Normally you use a pivot table to link two items together. So let me suggest something like this:
Does a patch belong to a single user? If so you should add a user_id to the patch table.
patch
id
user_id
area_id
title
Can an a Patch be in multiple areas? I kind of doubt it, so I'd add an area_id as well.
class User extends Model {
public function patchs() {
return $this->hasMany('App/Patch', 'user_id');
}
}
class Patch extends Model {
public function area() {
return $this->belongsTo('App\Area', 'area_id');
}
}
class Area extends Model {
public function patchs() {
return $this->hasMany('App\Patch', 'patch_id');
}
}
Then you can start referencing your patchs like:
$patchs = User::find(1)->patchs()
or the area that a patch belongs to by
Patch::find(1)->area()
and all the patchs in an area by
Area::find(1)->patchs()
Does this help?

Related

How to join two tables with a pivot table using Laravel?

I have these three tables:
tbl_lista_contactabilidad tbl_equipo_postventaatc users
------------------------- ----------------------- -----
id id id
usuarios_id asesor_id name
tbl_lista_contactabilidad.usuarios_id should be related with tbl_equipo_postventaatc.asesor_id. asesor_id should be the "pivot" between tbl_lista_contactabilidad.usuarios_id and users.id to make the relation.
I want to make this relation so I tried to do this relation in this way (I will put only the relation of the model)
Tbl_Lista_Contactabilidad (Model 1)
public function postventaatc(){
return $this->belongsTo('App\Models\Tbl_EquipoPostventaatc','usuarios_id');
}
Tbl_Equipo_Postventaatc (Model 2) -> This should be the pivot model
public function contactabilidad(){
return $this->hasMany('App\Models\Tbl_Lista_Contactabilidad','usuarios_id');
}
public function user(){
return $this->belongsTo('App\Models\User','asesor_id');
}
User (Model 3)
public function postventaatc(){
return $this->hasMany('App\Models\Tbl_Lista_Postventaatc','asesor_id');
}
EXAMPLE:
As you see in the image... if I relate usuarios_id with users directly I will get another name and I don't want that... I want the relation just like in the image
A pivot table is a structure used to join two separate models together with a single relationship. This is called a many-to-many relationship in Eloquent.
From what you've described, this is not the case here. Rather, it looks like a has-many-through relationship.
If I'm understanding correctly, your relationships should look like this:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Tbl_Lista_Contactabilidad extends Model {
protected $table = 'tbl_lista_contactabilidad';
public function postventaatc() {
return $this->belongsTo(Tbl_EquipoPostventaatc::class, 'usuarios_id');
}
}
class Tbl_EquipoPostventaatc extends Model {
protected $table = 'tbl_equipo_postventaatc';
public function contactabilidad() {
return $this->hasMany(Tbl_Lista_Contactabilidad::class, 'usuarios_id');
}
}
class User extends Model {
public function postventaatc() {
return $this->belongsTo(Tbl_EquipoPostventaatc::class, 'asesor_id');
}
public function contactabilidad() {
return $this->hasManyThrough(Tbl_Lista_Contactabilidad::class, Tbl_EquipoPostventaatc::class, 'asesor_id', 'usuarios_id');
}
}
Obviously this is easier for a native English speaker, but I cannot stress how much easier this would be if you were following the Laravel rules around naming your models, tables, and columns. Why does usuarios_id column relate to a table called tbl_equipo_postventaatc? Why use asesor_id instead of user_id? 🤷🏽‍♂️ Those names have nothing to do with each other, and make it hard to figure out what is going on.

LARAVEL ELOQUENT - I want to add column from user table to a relation table

I am not much familiar with eloquent orm in laravel
I have 3 tables they are
-- leads
|
Lead_appointments
and users table
since lead_appointments belongs to leads references id on leads by lead_id
the leads_appointments has a column called created_by with user's id in it
I am trying to query user's name and email along with the result as another column when query using eloquent
Lead Model
class Leads extends Model
{
public function appointments()
{
return $this->hasMany('App\Models\LeadsAppointments', 'lead_id');
}
}
My eloquent query in controller
return $this->lead->with('appointments')->find($id);
the result is like this
In under appointments i also want user email and name along with created by in it
But I couldn't figure it out
Add a relation to LeadAppointment model like this:
class LeadAppointment extends Model
{
public function users()
{
return $this->belongsTo('App\Models\User', 'created_by');
}
}
and change leads model like this:
class Leads extends Model
{
public function appointments()
{
return $this->hasMany('App\Models\LeadsAppointments', 'lead_id')->with('users');
}
}

Make a simple join to a reference table with Laravel 5.1 Eloquent

I have a simple join to make, but I can't do it.
I have a tournament that has a categoryId field in the table.
The table TournamentLevel is a 10 entry table.
So I would like to be able to retrieve level->name with Eloquent.
I tried to do the following:
In Tournament, I tried to define a hasOne relationship:
class Tournament extends Model
{
....
public function level()
{
return $this->hasOne('App\TournamentLevel');
}
But then, Eloquant is looking for tourmanent_id inside of TournamentLevel Table
So I tried the opposite,
In Model TournamentLevel:
class TournamentLevel extends Model
{
...
public function tournament()
{
return $this->belongsTo('App\Tournament');
}
}
And tried to reach :
tournament->level->name
but without success
It seems pretty elementary, but I can't do it... Any idea???

laravel4 one to one relationship can not load the relationship

I have two tables like this:
users
id email
1 abc#ibm.com
2 abc#hp.com
3 abc#google.com
grp_members
grp_id user_id
1 2
2 2
13 1
13 3
2.My model
There, one group member must be a user, so its a one to one relationship just for GroupMember.
Users model about table users
class Users extends Eloquent {
protected $table = "users";
}
GroupMember model about table group_members
class GroupMember extends BaseModel{
protected $table = "grp_members";
public function user(){
return $this -> hasOne('Users', 'id');
}
}
3.In my service GroupApi.php, if I have a query like this
class GroupApi {
public function queryGroupMembers(){
$result = GroupMember::all();
var_dump(get_class(GroupMember::all())); //CODE ONE
foreach($result as $ret){
var_dump(get_class($ret)); //CODE TWO
var_dump(get_class($ret -> user)); //CODE THREE
}
}
}
As you see, when I invoke var_dump(get_class(GroupMember::all())) at CODE ONE,
I got this
.string(39) "Illuminate\Database\Eloquent\Collection"
Yes, that's what I want.
Now, at CODE TWO, it prints
string(11) "GroupMember"
Yes, also correct object, but when the code goes to CODE THREE, it give me a surprise,
the outputs like this:
string(8) "GroupApi"
Why its an instance of GroupApi, but not the instance of Users or GroupMember
And in that case , how can I invoke $ret -> user?
Any idea is welcome, thanks very much.
There are some things I'm not sure I understand in your implementation but something that could be causing you troubles is not using the conventions Laravel asks for, that being using User as the model name and users (model + s) as the table name.
Also, i would guess $g1 is not a GroupMember object as you suggest, could you getClass() it and comfirm?
Ok, I guess you have 3 tables:
users; grp_members; groups
and a many-to-many relationship between users and groups using the table grp_members as pivot table.
In this case, try this:
Class User:
class User extends Eloquent {
public function groups()
{
return $this->belongsToMany('Group', 'grp_members');
}
}
Class Group:
class Group extends Eloquent {
public function users()
{
return $this->belongsToMany('User','grp_members');
}
}
And also change the field name in the table 'grp_members' from grp_id to group_id, to follow eloquent conventions.

Eloquent with multiple relations

I'm new to Laravel and ORMs in general, so this is probably a very basic concept that I'm missing. I have three tables that I'm trying to define a relation with using Laravel 4's Eloquent ORM. Here's the slimmed-down table definitions:
stores
id (PK)
name
postal_codes
id (PK)
postal_code
city
state
country
locations
id (PK)
store_id (FK => stores.id)
postal_code_id (FK => postal_codes.id)
*additional location-specific fields such as address, phone #, etc
The stores table has a one to many relationship with the locations table, so I can use $this->hasMany("Location") in the Stores model, and $this->belongsTo("Store") in the Location model.
My question is, how do I define the relation between locations and postal_codes in their respective models? The locations table has a many-to-one relationship with the postal_codes table. Ideally I want to be able to do something like this: $store->locations()->first()->city. Is this possible?
Aren't you looking for something like:
class Locations
{
public function city()
{
return $this->belongsTo('PostalCode');
}
}
So now you can call $store->locations()->first()->city. This will return a PostalCode model, if you want to return just the city:
public function getCity()
{
return $this->city()->city;
}
And then you call $store->locations()->first()->getCity().
You could go further and create a __get() magic method so it calls everything dynamically.
It sounds like you have a many-to-many relationship between Stores and Postal_Codes. This would be demonstrated this way in Laravel:
class Store extends Eloquent {
public function postal_codes() {
$this->belongsToMany('Postal_Code', 'location');
}
}
class Postal_Code extends Eloquent {
public function stores() {
$this->belongsToMany('Store', 'location');
}
}
For more info, try this link: Laravel Many-to-Many Relationships.
I believe you are looking for a polymorphic relation.
Modify your locations table to include id, imageable_id, imageable_type, and then whatever additional location information you need. The imageable_id field will contain the ID of whatever you are looking for in it's respective table and the imageable_type will be whatever the name of that model for that table is.
On your models...
Class Location extends Eloquent
{
public function imageable()
{
return $this->morphTo();
}
}
Class Store extends Eloquent
{
public function locations()
{
return $this->morphMany('Location','imageable');
}
}
Class PostalCode extends Eloquent
{
public $table = 'postal_codes';
public function locations()
{
return $this->morphMany('Location','imageable');
}
}
And now, it's possible to retrieve all of the locations for the stores or postal codes with something like
$store = Store::find(1);
foreach($store->locations as $location)
{
//
echo $location->city;
}
$postalCode = PostalCode::find(1);
foreach($postalCode->locations as $location)
{
//
echo $location->city;
}

Categories