How to create a hasManyTrough Eloquent relationship in this database schema? - php

I have the following tables
products
variants
attributes
options
option_variant
Look at this sqlfiddle for details http://sqlfiddle.com/#!2/eb1c73/24/0
Can I have something like this on my Product model to get all the attributes like I'm doing on the sqlfiddle query?
function attributes(){
return $this->hasManyThrough('Attributes','Variant');
}
THANKS!!
My Models:
<?php
class Product extends \Eloquent {
protected $table = 'products';
public function user()
{
return $this->belongsTo('User');
}
public function variants()
{
return $this->hasMany('Variant');
}
public function attributes(){
return $this->hasManyThrough('Attribute','OptionVariant');
}
}
<?php
class Variant extends \Eloquent {
protected $table = 'variants';
public function product()
{
return $this->belongsTo('Product');
}
public function options()
{
return $this->belongsToMany('Option');
}
}
<?php
class Attribute extends \Eloquent {
protected $table = 'attributes';
public function options()
{
return $this->hasMany('Option');
}
}
<?php
class Option extends \Eloquent {
protected $table = 'options';
public function attribute()
{
return $this->belongsTo('Attribute');
}
public function variants()
{
return $this->belongsToMany('Variant');
}
}
<?php
class OptionVariant extends \Eloquent {
protected $table = 'option_variant';
}

If you want take all atributtes all time that you select the products:
In Product model:
$with = ['attributes'];
In Controller:
$products = $this->product->findAll();
return View::make('products.index', compact('products'));
In View:
#foreach($products as $product)
{{ $product->attributes->column1 }}
#endforeach

Related

Php Laravel get relation inside relation

I have a problem, I am trying to retrieve orders with products from my database. The idea is that you have an order with products in it and a product can have options with different options. For example a big mac menu has different options, such as size with three different options. This is what I have now:
OrderModel:
class Order extends Model
{
use HasFactory;
protected $table = 'orders';
public function user()
{
return $this->belongsTo(User::class);
}
public function table()
{
return $this->belongsTo(Table::class);
}
public function branch()
{
return $this->belongsTo(Branch::class);
}
public function products()
{
return $this->belongsToMany(Product::class)->withPivot('quantity');
}
}
OrderProduct:
class OrderProduct extends Pivot
{
use HasFactory;
public $incrementing = true;
protected $table = 'order_product';
public function options()
{
return $this->hasMany(OrderProductOptions::class);
}
public function products()
{
return $this->hasMany(Product::class);
}
}
OrderProductOptions:
class OrderProductOptions extends Model
{
use HasFactory;
public $incrementing = true;
protected $table = 'order_product_options';
public function options()
{
return $this->belongsTo(OrderProductsOptionsOptions::class);
}
}
OrderProductsOptionsOptions:
class OrderProductsOptionsOptions extends Model
{
use HasFactory;
protected $table = 'order_products_options_options';
public function Option()
{
return $this->belongsTo(OrderProductOptions::class);
}
}
When I want to pick up an order with products and selected options like this:
$newOrder = Order::with('products.options')->findOrFail($order->id);
I get all the options that the product has, how do I get only the selected ones that belong to the order?
see laravel document , you must define foringPivotKey and relatedPivot key like this:
return $this->belongsToMany(Role::class, 'role_user', 'user_id', 'role_id');

how to access a function from model file

im using laravel 7.24 and php 7.4 on my project
What i want to is fundementally creating relations between 3 table and using them in 'one' query.
to be specific i need to access 'ordered products' from my order detail page.
public function orderdetail($id)
{ //certainorder model access to 'ShoppingCard'model from below
$orderDetails = CertainOrder::with('ShoppingCard.shoppingCardProducts.product')
->where('ShoppingCard.id' , $id)->firstorFail();
return view('orderdetails', compact ('orderDetails'));
}
CertainOrder model access to 'ShoppingCard' model from top and in the ShoppingCard model it contains shoppingCardProducts function which you will see in below and with shoppingCardProducts function my 'products' table had a relation. the problem is something in relations is wrong and i can't get data from shoppingcardproduct
class ShoppingCard extends Model
{
protected $table = "shopping_card";
protected $fillable = ['id', 'user_id', 'created_at','updated_at'];
public function shoppingCardProducts()
{
return $this->hasMany('App\ShoppingCardProduct');
}
class CertainOrder extends Model
{
protected $table = "certain_orders";
protected $guarded = [];
public function shoppingCard()
{
return $this->belongsTo(ShoppingCard::class, 'sepet_id');
//sepet_id is a foreign key.
}
class ShoppingCardProduct extends Model
{
use SoftDeletes;
protected $table = "shopping_card_product";
protected $fillable = ['id', 'sepet_id', 'urun_id','quantity','price','status','created_at','updated_at','deleted_at'];
public function product()
{
return $this->belongsTo('App\Product');
}
I think you missed it somewhere in the code
class ShoppingCard extends Model
{
protected $table = "shopping_card";
protected $fillable = ['id', 'user_id', 'created_at','updated_at'];
public function shoppingCardProducts()
{
return $this->hasMany('App\ShoppingCardProduct');
}
public function CertainOrder(){
return $this->hasMany('path\to\model');
}
public function ShoppingCardProduct(){
return $this->hasMany('path\to\model');
}
}
class CertainOrder extends Model
{
protected $table = "certain_orders";
protected $guarded = [];
public function shoppingCard()
{
return $this->belongsTo('App\path\to\model', 'sepet_id');
//sepet_id is a foreign key.
}
}
class ShoppingCardProduct extends Model
{
use SoftDeletes;
protected $table = "shopping_card_product";
protected $fillable = ['id', 'sepet_id', 'urun_id','quantity','price','status','created_at','updated_at','deleted_at'];
public function ShoppingCard()
{
return $this->belongsTo('App\ShoppingCard');
}
}
and make the call this way
public function orderdetail($id)
{ //certainorder model access to 'ShoppingCard'model from below
$orderDetails = ShoppingCard::with('CertainOrder, ShoppingCardProduct')
->where('id' , $id)->firstorFail();
return view('orderdetails', compact ('orderDetails'));
}

Laravel comments and user relationship returns null

I'm trying to implement commenting system on my website but i'm having hard time with the relationships. for some reason when i try to access the user relation from the comment class it returns null.. my code:
Post.php
class Post extends Model
{
public $timestamps = false;
public $primaryKey = 'post_id';
protected $fillable = ['title','created_at','username','image'];
public function user()
{
return $this->belongsTo(User::class,'username');
}
public function votes()
{
//Quick note: Id refers to the post id.
return $this->hasMany(PostVotes::class,'post_id');
}
public function comments()
{
return $this->hasMany(Comment::class,'post_id');
}
}
User.php
class User extends Model implements Authenticatable
{
use AuthenticableTrait;
protected $primaryKey = 'username';
public $incrementing = false;
public $timestamps = false;
protected $fillable = ['username','email','password','created_at','avatar','about'];
// Gets avatar to display on navbar.
public function posts()
{
return $this->hasMany(Post::class,'username');
}
public function comments()
{
return $this->hasMany(Comment::class,'username');
}
public static function getAvatar()
{
return self::Where('username', '=', Session::get('username'))->value('avatar');
}
}
Comment.php
class Comment extends Model
{
public $timestamps = false;
public $primaryKey = 'post_id';
protected $fillable = ['comment','created_at','post_id','username'];
public function user()
{
$this->belongsTo(User::class,'username') ;
}
public function post()
{
$this->belongsTo(Post::class,'post_id');
}
}
public function view($post_id)
{
$post = Post::with('comments')->findOrFail($post_id);
return view('posts.view',compact('post'));
}
#foreach($post->comments as $comment)
// null
{{dd($comment->user())}}
#endforeach
Use missed the return keyword
public function user()
{
return $this->belongsTo(User::class,'username') ;
}
public function post()
{
return $this->belongsTo(Post::class,'post_id');
}
public function displaycomment($id) {
$data['comment'] = comment::select('comments.id', 'comments.description', 'users.name', 'comments.created_at', 'comments.post_id')->where('post_id',$id)->leftjoin('users', 'users.id', '=', 'comments.user_id')->get();
// dd($data);
return view('displayblog', compact('data'));
}

Fetching Featured Posts with Review and Tag Laravel

I have 4 Eloquent.
class Featured extends \Eloquent {
protected $fillable = array('*');
public function courses() {
return $this->belongsTo('Course');
}
}
class Course extends \Eloquent {
protected $fillable = array('*');
public function featured() {
return $this->hasMany('Course');
}
public function review() {
return $this->hasMany('Course');
}
public function tag() {
return $this->hasMany('Course');
}
}
class Tag extends \Eloquent {
protected $fillable = array('*');
public function courses() {
return $this->belongsTo('Course');
}
}
class Review extends \Eloquent {
protected $fillable = array('*');
public function courses() {
return $this->belongsTo('Course');
}
}
I need to fetch all the featured courses, their review and tags.
Is it possible in 1 query? I have to show some featured posts on front page with their respective reviews and their tags.
This is Laravel 4.
You can use
Course::where('feature',1)->with('review')->with('tags')->get();
feature is a Column which tell course is feature or not.

Laravel 5 hasManyThrough

I have 3 tables: company <-> users <-> invoice.
A company hasMany users.
A user belongsTo a company and, and a user hasMany invoices.
An invoice belongsTo a user.
Now I have an invoice with information about user (customer), and I want to get the user its information about the company so I made an:
An invoice hasManyThrough users, company (so gets the company through user)
Now it doesn't work as it is needed.
Models:
class Company extends Eloquent {
protected $table = 'companies';
public function users()
{
return $this->hasMany('App\User', 'id');
}
public function invoices()
{
return $this->hasManyThrough('App\Company', 'App\User');
}
}
class User extends Model {
protected $table = 'users';
public function usertype()
{
return $this->belongsTo('App\UserType','usertype_id','id');
}
public function company()
{
return $this->belongsTo('App\Company','company_id','id');
}
public function invoice()
{
return $this->hasMany('App\Invoice');
}
}
class Invoice extends Model {
protected $table = 'invoices';
public function users() {
return $this->belongsTo('App\User', 'id');
}
}
Invoice Controller:
class InvoiceController extends Controller {
private $invoice;
public function __construct(Invoice $invoice)
{
$this->invoice = $invoice;
}
public function index(Invoice $invoice)
{
$invoices = $invoice->with('users', 'company')->get();
dd($invoices);
return view('invoice.index', compact('invoices'));
}
public function create()
{
//
}
public function store()
{
}
public function show($id)
{
$invoice = Invoice::with('users')->find($id);
return view('invoice.show', compact('invoice'));
}
public function edit($id)
{
//
}
public function update($id)
{
//
}
public function destroy($id)
{
//
}
}
The dd($invoices) will give a BadMethodCallException
Call to undefined method Illuminate\Database\Query\Builder::company()
Any further needed information can be provided!
Let's say we have table A and B and C
where table A has many of B (OneToMany) and B has many of C (OneToMany)
inorder to access the table C from table A you can use the Laravel shortcut (HasManyThrough) on the Table A and the problem is solved
BUT If you have table A and B and C
where table A has many of B (OneToMany) and B has many of C (ManyToMany)
you cannot use the laravel's (HasManyThrough) shortcut to access the table C from table A, {because of the pivot table in the middle between B and C} what you can do in this case is very simple:
In this example table A will be [courses], table B will be [chapters], and table C will be [videos]
where every course has may chapters, while a chapter can belong to only one course. in the other hand every chapter has many videos while a video can belong to many chapters.
<?php namespace Moubarmij\Models;
use Eloquent;
class Video extends Eloquent{
protected $table = 'videos';
/*************************************************************
* Query Scopes
**************************************************************/
public function scopePublished($query)
{
return $query->where('published', '=', '1');
}
public function scopeOrdered($query)
{
return $query->orderBy('order_number', 'ASC');
}
/*************************************************************
* Relations
**************************************************************/
public function chapters()
{
return $this->belongsToMany('Moubarmij\Models\Chapter', 'chapters_videos');
}
}
<?php namespace Moubarmij\Models;
use Eloquent;
class Chapter extends Eloquent{
protected $table = 'chapters';
/*************************************************************
* Query Scopes
**************************************************************/
public function scopePublished($query)
{
return $query->where('published', '=', '1');
}
public function scopeOrdered($query)
{
return $query->orderBy('order_number', 'ASC');
}
public function scopeWithVideos($query)
{
return $query->with(['videos' => function($q)
{
$q->ordered();
}]);
}
/*************************************************************
* Relations
**************************************************************/
public function course()
{
return $this->belongsTo('Course');
}
public function videos()
{
return $this->belongsToMany('Moubarmij\Models\Video', 'chapters_videos');
}
}
<?php namespace Moubarmij\Models;
use Eloquent;
class Course extends Eloquent{
protected $table = 'courses';
/*************************************************************
* Query Scopes
**************************************************************/
public function scopeVisible($query)
{
return $query->where('visible', '=', '1');
}
public function scopeOrdered($query)
{
return $query->orderBy('order_number', 'ASC');
}
public function scopeWithChapters($query)
{
return $query->with(['chapters' => function($q)
{
$q->ordered();
}]);
}
public function scopeWithChaptersAndVideos($query)
{
return $query->with(['chapters' => function($q)
{
$q->ordered()->withVideos();
}]);
}
/*************************************************************
* Relations
**************************************************************/
public function chapters()
{
return $this->hasMany('Moubarmij\Models\Chapter');
}
}
You can also do this in the Course class, so when you use ->with('chapters'), it automatically loads the videos too:
public function chapters()
{
return $this->hasMany('Moubarmij\Models\Chapter')->with('videos');
}

Categories