I have 5 tables
Products
-- Categories
--- SubCategories
---- Marks
----- Suppliers
I want to know how to make relationship
I have Product Model structure with :
namespace App\Models\Products;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
use HasFactory;
protected $fillable = [.... ];
public function categorie(){
return $this->belongTo(categories::class);
}
public function sub_categorie(){
return $this->belongTo(sub_categorie::class);
}
public function marks(){
return $this->belongTo(marks::class);
}
public function suppliers(){
return $this->belongTo(suppliers::class);
}
}
i want to know if it's correct ?
Another Question how would be looks other Model relationships such Suppliers, Categories, SubCategories ...
It depends on the cardinality and the foreign_keys that are involved.
Products
-- Categories
--- SubCategories
---- Marks
----- Suppliers
The context that you gave me, I'm guessing that each table depends on the previous one as showed in the context that you gave. If so, then you can do the following:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Suppliers extends Model
{
protected $fillable = [.... ];
public function mark()
{
return $this->belongsTo(Mark::class);
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Marks extends Model
{
protected $fillable = [.... ];
public function subCategorie()
{
return $this->belongsTo(SubCategorie::class);
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class SubCategory extends Model
{
protected $fillable = [.... ];
public function categorie()
{
return $this->belongsTo(Categorie::class);
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Categorie extends Model
{
protected $fillable = [.... ];
public function categorie()
{
return $this->belongsTo(Product::class);
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $fillable = [.... ];
}
For more in depht inormation, you can consult the section about relationshipts on laravel docs: https://laravel.com/docs/8.x/eloquent-relationships.
Please use the correct nomeclature of relationship's, instead of "categorie" write "category" in the function name, with that laravel will automaticaly recognise the foreign key.
Example:
public function category(){
return $this->belongTo(categories::class);
}
public function sub_category(){
return $this->belongTo(SubCategory::class);
}
public function mark(){
return $this->belongTo(Mark::class);
}
public function supplier(){
return $this->belongTo(Supplier::class);
}
Show me your models folder please if you have any problem .
Related
there is a (card model) bleongsToMany contacts, and there is a (contact model) is bleongsToMany cards, I want when (card) get updated his children in the middle table in the relation became removed.
I'm trying to do this by using (the observer), I did all steps correctly but the issue is:
when (card model) updated his children still exist in the middle table of the relationship, I want to remove them when any update on the card.
Route:
Route::get('/test',function(){
$card = \App\Models\Card::find(1);
$card-> update([
'name' => 'firstCard1',
'user_name' =>1,
]);
return true;
});
Observer:
<?php
namespace App\Observers;
use App\Models\Card;
class CardObserver
{
public function updated(Card $card)
{
$card -> contact()-> delete();
}
}
Card Model:
<?php
namespace App\Models;
use App\Observers\CardObserver;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Card extends Model
{
use HasFactory;
protected $fillable = [
'name',
'user_id ',
];
public $timestamps = true;
protected $hidden = ['pivot'];
public function contact()
{
return $this->belongsToMany(Contact::class, 'card_contacts', 'card_id');
}
public function connection()
{
return $this->belongsTo(Connection::class, '');
}
protected static function boot()
{
parent::boot();
Card::observe(CardObserver::class);
}
}
Contact Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Contact extends Model
{
use HasFactory;
protected $fillable = [
'provider_id',
'user_id',
'contact_string'
];
public $timestamps = true;
protected $hidden = ['pivot'];
public function card(){
return $this->belongsToMany(Card::class,'card_contacts','contact_id');
}
public function user(){
return $this->belongsTo(User::class,'user_id');
}
public function provider(){
return $this->belongsTo(Provider::class,'provider_id');
}
}
Card_contact Model (the pivot table):
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class CardContact extends Model
{
use HasFactory;
protected $fillable = [
'card_id',
'contact_id',
];
public $timestamps = true;
}
any help please?
I'm trying to implement a belongsToMany relationship, where I need to list products and right after the name of the same, the relationship is made between 3 tables, order, description and order_product.
As you can realize the field appears empty.
This is my belongsToMany relation:
Description Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Order;
class Description extends Model
{
protected $table = 'erp_product_description';
protected $primaryKey = 'erp_productid';
protected $fillable = ['erp_name'];
public $timestamps = false;
public function product()
{
return $this->belongsTo('App\Product', 'erp_productid','erp_productid');
}
public function order()
{
return $this->belongsToMany('App\Order', 'erp_order_product', 'erp_productid', 'erp_createdid');
}
}
Order Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
protected $table = 'erp_order';
protected $fillable = ['erp_createdid'];
public function description()
{
return $this->belongsToMany('App\Description', 'erp_order_product', 'erp_createdid', 'erp_productid');
}
}
I used the Laravel 'DebugBar' plugin to see which query is running and returned this:
select `erp_product_description`.*, `erp_order_product`.`erp_createdid` as `pivot_erp_createdid`, `erp_order_product`.`erp_productid` as `pivot_erp_productid` from `erp_product_description` inner join `erp_order_product` on `erp_product_description`.`erp_productid` = `erp_order_product`.`erp_productid` where `erp_order_product`.`erp_createdid` is null
Why my query received null in value? Any suggestion?
I am not sure what is going on here. I am getting returns of null despite having the info in the database.
Stimuli Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Stimuli extends Model
{
protected $table = 'stimuli';
public $timestamps = false;
/**
* Get the details associated with the stimulus
*/
public function info()
{
return $this->hasMany('App\StimuliInfo', 'attribute', 'value');
}
}
StimuliInfo Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class StimuliInfo extends Model
{
/**
* Get the stimuli associated with the detailss
*/
protected $table = 'stimuli_info';
public $timestamps = false;
public function info()
{
return $this->belongsTo(Stimuli::class);
}
}
Controller
<?php
namespace App\Http\Controllers;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use App;
use Illuminate\Http\Requests;
class Labels extends Controller
{
public function index()
{
}
public function objects()
{
$stimulus = App\Stimuli::with('info')->get();
foreach ($stimulus as $stim)
{
$stimuli[] = $stim->stimulus_id;
}
return $stimuli;
shuffle($stimuli);
return view('label/objects')->with(compact('stimuli'));
}
}
Okay, so here is a test controller. For some reason, I am getting a null output for every data point. Which is odd as I can see in the DB that there is data there which is not null.
I am wondering whether I am doing something fishy in the model that is not right outputting this data.
Any help would be greatly appreciated - I am at a loss for this process
I am just starts a project in laravel and this is new environment for me. I am familiar with PHP and also models relationship. But the laravel structure is little bit complex for starting.
So the problem is I have a question and Course table, A single question may have more then one course so i created one more table which hold course id and question id.
Question Model
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Question extends Model{
protected $primaryKey = "id";
public function courses(){
return $this->hasMany('App\Models\CourseQuestion');
}
}
Course model
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Course extends Model {
protected $primaryKey = "id";
public function questions(){
return $this->hasOne('App\Models\CourseQuestion');
}
}
And last courseQuestion model
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class CourseQuestion extends Model {
protected $primaryKey = "id";
public function questions(){
return $this->hasOne('App\Models\Question');
}
public function courses(){
return $this->hasMany('App\Models\Course');
}
}
And my controller where i getting result -
class IndexController extends BaseController {
public function index(){
$user = Question::with('user','courses','branches')->find(100);
echo "<pre>";
print_r($user); die;
}
}
So the courses return only id of course and questions which store in third table but i want the course name respective id. Please help
Thanks.
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Question extends Model
{
protected $primaryKey = "id";
public function courses()
{
return $this->hasMany('App\Models\CourseQuestion', 'course_question_id', 'id')
->select('id', 'name');
}
}
I have two tables
products and users
Both of this objects has images associated with it in a table
images
The schema for the images table is
id | image_id | resource_id | flag
1 | 567575 | 1 | user
2 | 423423 | 1 | product
Based on this flag i am identifying whether its a users image or whether its a products image.
If I need to eager load a users image how do it do it?
User model
<?php
namespace App\Entities;
use Illuminate\Database\Eloquent\Model;
class User extends Model implements Transformable
{
use TransformableTrait;
protected $table = 'users';
protected $primaryKey = 'users_id';
public function images()
{
return $this->hasMany('App\Entities\Image','resource_id');
}
}
Product model
<?php
namespace App\Entities;
use Illuminate\Database\Eloquent\Model;
class Product extends Model implements Transformable
{
use TransformableTrait;
protected $table = 'products';
protected $primaryKey = 'products_id';
public function images()
{
return $this->hasMany('App\Entities\Image','resource_id');
}
}
images model
<?php
namespace App\Entities;
use Illuminate\Database\Eloquent\Model;
class Image extends Model implements Transformable
{
use TransformableTrait;
protected $table = 'images';
protected $primaryKey = 'images_id';
public function products()
{
return $this->hasOne('App\Entities\Product','products_id');
}
public function users()
{
return $this->hasOne('App\Entities\User','users_id');
}
}
Is there a way I can pass a flag in the relationship function of images() so that it will fetch the record based on the flags?
Please help out.
You can try this adding a conditional inside your images() method:
<?php
namespace App\Entities;
use Illuminate\Database\Eloquent\Model;
class User extends Model implements Transformable
{
use TransformableTrait;
protected $table = 'users';
protected $primaryKey = 'users_id';
public function images($filtered=false)
{
if ($filtered) {
return $this->hasMany('App\Entities\Image','resource_id')->where('flag','user');
}
return $this->hasMany('App\Entities\Image','resource_id');
}
}
and try the same logic to your Product model
Change your Image model to:
<?php
namespace App\Entities;
use Illuminate\Database\Eloquent\Model;
class Image extends Model implements Transformable
{
use TransformableTrait;
protected $table = 'images';
protected $primaryKey = 'images_id';
public function product()
{
return $this->belongsTo('App\Entities\Product', 'products_id', 'resource_id');
}
public function user()
{
return $this->belongsTo('App\Entities\User', 'users_id', 'resource_id');
}
}
try with this way :
$user_id = 1;
$my_image= User::find($user_id)->images()->where('flag', '=', 'user')->first();