Laravel 5.3 : 2 same relationships for 2 same Tables - php

i need help for make something : I have 2 table :
- Users
----------
id_user
- Sports
----------
id_sport
title_sport
User can practice 1 or more sport.
User can search user who practice 1 or more sport.
Can you help me please for the model User?

Can i use something like this ?
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function pratice()
{
return $this->belongsToMany('App\Sport');
}
public function search_user()
{
return $this->belongsToMany('App\Sport');
}
}
with 2 pivots table.

Related

Laravel Eloquent Model change table name on runtime in a related instance

I am new to Laravel and also asked the question on Laracast without any success so far.
Here is my problem: I have a database layout something like this:
Table: categoryA_products
Table: categoryB_products
Table: categoryC_products
and per default the Laravel user table:
Table: user
I have create a two Laravel Eloquent models:
Product:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
// protected $table = '';
public function users()
{
return $this->belongsTo( User::class );
}
}
User:
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function products()
{
return $this->hasMany( Product::class );
}
}
As each product has a different table name I would normally create 1 model for each table but as they are all similar I would like to define the model table name at runtime.
I know I can do this with "$product->setTable()" but as I use the "newRelatedInstance" class from Laravel (hasMany and belongsTo) I cannot initiate the product class and set the table.
Is there a workaround for this?
Yes, I am aware that I could create a category table and link the products to each category but this is a fictional database model. There is a reason for this approach and I can explain it more in detail if needed. That said it make sense for this sample but I cannot use it for the live database.
I have a working solution with a model for each "category" but this is very messy.
Any help would be appreciated.
Since you're unable to load the relations, you could try referencing and re-initializing them like:
$relations = $product->getEagerLoads();
$attributes = $product->getOriginal();
table_name = 'categoryA_products'; // or categoryB_products or categoryC_products
$product->newQuery()
->newModelInstance($attributes)
->setTable($table_name)
->setEagerLoads($relations)
->...

one to many relationships in laravel

Each industry has many projects
each project belongs to only one industry
industries table has columns as below:
id, industry_name, industry_code, created_at, updated_at
projects table has columns as below:
id, industry_id (foreign key), user_id, project_name, project_start_date, project_end_date, created_at, updated_at
I want to show project name and industry name in my index.blade.php (view)
I have created Project & Industry models. How do I show the result in my view?
Industry.php model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Industry extends Model
{
public function project()
{
return $this->hasMany('App\Models\Project');
}
}
Project.php model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
public function industry()
{
return $this->belongsTo('App\Models\Industry');
}
}
like this ...
$Industry = App\Industry ::find(1);
echo $Industry ->Project ->project_name;
https://laravel.com/docs/5.5/eloquent-relationships#one-to-many
do try renaming your method "project" to "projects" in Industry.php since it is a "hasMany" relationship. this would prevent you from making errors.
in your controller, say PagesController.php
public function index() {
// find an industry with id of 1
$Industry = App\Industry ::find(1);
return view('some_view',compact('industry'));
}
therefore in your view, since an industry has many projects you can access them and loop over them by $Industry->projects. However you should consider eager loading them in order to prevent the n + 1 problem. there edit your query to $Industry = App\Industry ::with('projects')->find(1);
read more on eager loading https://laravel.com/docs/5.5/eloquent-relationships#eager-loading
https://laravel.com/docs/5.5/eloquent-relationships#one-to-many
If specifically you want only project_name and industry_name then
try this -
$result = App\Industry::with(array('projects'=> function($query){
$query->addSelect(['project_name']);
}))
->where('industry.id',$id)
->get([industry_name]);
else for all records try this -
$result = App\Industry::with('projects')
->where('industry.id',$id)
->get();
Hope this will help you.

Laravel: How do I create the relationship and which one do I use?

I have the database structure that have a classes table, a users table and users_classes table that matches the other two, because a user can belong to multiple classes. I have a problem now. I have code like this:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
class Classes extends Model
{
protected $table = 'classes';
public function students()
{
}
}
And I want to be able to access the students of the class by typing $class = Classes::find(1) and then $class->students to access the students. How do I define the relationship without using the query builder? I want to use eloquent. Im a noobie in Laravel pls dont downvote.
You use a belongsToMany relation.
If your users_classes table has the fields user_id and class_id you can do the following:
public function students()
{
return $this->belongsToMany(Student::class, 'users_classes', 'class_id', 'user_id');
}

Laravel 5 pivot tables are not working

I am trying to change the home page text languages from database using Pivot tables relationship.
All works fine and I am getting no errors but the word login is not shown.
I have 3 tables
languages
id | name | sign | default_back
1 | English | en | 1
2 | Russian | ru | 0
features
id | code | type
70 | login | 0
feature_language
id | feature_id | language_id | text
1 | 70 | 2 | Ru Login
2 | 70 | 1 | Login
Language Model
<?php // Languages Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Language extends Model
{
public function features(){
return $this->belongsToMany('App\Feature');
}
public function getDefaulLanguage(){
return $this->default_back;
}
public function featureTranslation($code){
return $this->features()->where('code', '=', $code)->first();
}
}
?>
Features Model
<?php // Features Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Feature extends Model
{
}
?>
Index controller
<?php // index controller
namespace App\Http\Controllers
use App\Language;
class HomeController extends Controller {
public function index(){
$languages = Language::get();
$language_default = Language::where('default_back', '>', '0')->first();
return view('index')->with('languages', $languages)
->with('language_default', $language_default);
}
}
?>
Index View
<?php
<h1>login : {{ $language_default->featureTranslation("login")->text}}</h1>
?>
Any help will be appreciated ))
First, you need to define your pivot table column name in your model.
Language Model:
public function features()
{
return $this->belongsToMany('App\Feature')->withPivot('text');
}
In you Index View, you need to access data like following:
{{ $language_default->featureTranslation("login")->pivot->text }}
Since your pivot table has extra column text, you need to define the column name while defining the relationship
According to Official Doc
By default, only the model keys will be present on the pivot object. If your pivot table contains extra attributes, you must specify them when defining the relationship:
public function features(){
return $this->belongsToMany('App\Feature')->withPivot('text');
}
And for Retrieving the intermediate table column, you need to use the pivot attribute.
Language Model
<?php // Languages Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Language extends Model
{
public function features(){
return $this->belongsToMany('App\Feature', 'feature_language', 'feature_id', 'language_id')->withPivot('text');
}
public function getDefaulLanguage(){
return $this->default_back;
}
public function featureTranslation($code){
return $this->features()->where('code', $code)->first()->pivot->text;
}
}
?>
Index View
<?php
<h1>login : {{ $language_default->featureTranslation("login") }}</h1>
?>

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.

Categories