hello friends need a hand with this query, failed to make it work, I'm new with laravel, I have 3 models:
DiscussCategory
class DiscussCategory extends Eloquent {
protected $table = 'discuss_category';
protected $guarded = array('id');
public function status() {
return $this->belongsTo('Status');
}
public function discuss() {
return $this->hasMany('Discuss');
}
}
Discuss
class Discuss extends Eloquent {
protected $table = 'discuss';
protected $guarded = array('id');
public function discussReplies() {
return $this->hasMany('DiscussReplies');
}
public function discussCategory() {
return $this->belongsTo('DiscussCategory');
}
public function users() {
return $this->belongsTo('Users');
}
}
Users
class Users extends Eloquent {
protected $table = 'users';
protected $guarded = array('id');
protected $hidden = array('password');
public function getAuthIdentifier() {
return $this->getKey();
}
public function getAuthPassword() {
return $this->password;
}
public function getReminderEmail() {
return $this->email;
}
public function discussReplies() {
return $this->hasOne('DiscussReplies');
}
public function discuss() {
return $this->hasMany('Discuss');
}
}
and this how I try to show the query in view
#foreach($data as $category)
{{$category->discuss->last()->users->nickname}}
#endforeach
if you run a foreach manages to get users, but I just want the name of the last user to post a discuss
Trying to get property of non-object
appreciate a hand, insurance is not much, but I have little experience
In your Discuss model change following method:
public function users() {
return $this->belongsTo('Users');
}
To this (use user not users)
public function user() {
// Assumed one discuss belongs to one user
return $this->belongsTo('Users'); // Rename Users to User and use User here
}
Also you should use singular name for all of your models for example, use User instead of Users.
Related
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');
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'));
}
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'));
}
class Article extends Model
{
protected $fillable = ['category_id','author_id','title','img','description','text'];
public function user()
{
return $this->belongsTo('App\User');
}
public function article_category()
{
return $this->belongsTo('App\ArticleCategory');
}
}
class ArticleCategory extends Model
{
protected $table = 'article_categories';
protected $fillable = ['name','hide'];
public function article()
{
return $this->hasMany('App\Article');
}
}
User model
public function article()
{
return $this->hasMany('App\Article');
}
Why am I getting error when trying to get author name and article category name?
Trying to get it in view this way:
$article->user->name
$article->article_category->name
Can't understand the reason :c
Try to change the
return $this->belongsTo('App\User');
and
return $this->belongsTo('App\ArticleCategory');
To
return $this->belongsTo('App\User', 'foreign_key');
and
return $this->belongsTo('App\ArticleCategory', 'foreign_key);
Both will receive the properly foreign key that you provide in yours tables on migrations. Perhaps your foreign keys doesn't recognized.
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');
}