How to convert the raw sql command on Laravel ORM Eloquent - php

I have 4 tables, 1->user, 2->category, 3->comment, 4->post
I want to get the category for the related post that user already commented
SELECT kategoris.* FROM kategoris
INNER JOIN yazis on yazis.kategori_id = kategoris.id
INNER JOIN yorums on yorums.yazi_id = yazis.id
INNER JOIN users on users.id = yorums.user_id
where users.id = 1
Relations

Depending on how your models are setup, this is how the query should be with Eloquent
$category = Post::whereHas('comments', function($query) {
$query->where('user_id', auth()->user()->id);
})->first()->category;
Update:
This is how your models and table migrations should look
User has many posts and comments
public function posts()
{
return $this->hasMany(Post::class);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
Category has many posts
public function posts()
{
return $this->hasMany(Post::class);
}
Post belongs to a category and a user, has many comments
public function category()
{
return $this->belongsTo(Category::class);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
Posts Table Migration
Schema::create('posts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->unsignedBigInteger('category_id');
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
$table->timestamps();
});
Comment belongs to a post and a user
public function post()
{
return $this->belongsTo(Post::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
Comments Table Migration
Schema::create('comments', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->unsignedBigInteger('post_id');
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
$table->timestamps();
});
Let's populate some data like this...
Database Seeder
$user = factory(User::class)->create([]);
$category = Category::create([]);
$post = $user->posts()->create(['category_id' => $category->id]);
$post->comments()->create(['user_id' => $user->id]);
And get the category of the post that the authenticated user commented on with the query above...
Hope this helps :)

Related

Laravel WhereHas only the latest record on the HasMany Relationship

I have Items table that has relation to Histories table.
I want to get count of items that has only latest history.status
I still can't get the exact same count result because its always count all of the histories not the latest one
Here is my code:
create_items_table.php
Schema::create('items', function (Blueprint $table) {
$table->id();
$table->string('code');
$table->string('name');
$table->longText('description')->nullable();
$table->longText('picture')->nullable();
$table->timestamps();
});
create_histories_table.php
$table->foreignId('item_id')->constrained();
$table->string('status')->nullable();
$table->longText('description')->nullable();
$table->dateTime('date')->nullable();
model of Item.php
public function histories(){
return $this->hasMany(History::class);
}
public function latestHistory(){
return $this->hasOne(History::class)->latest();
}
model of History.php
public function item()
{
return $this->belongsTo(Item::class);
}
MyController.php
$items_status['good'] = Item::with('latestHistory')->whereHas('latestHistory', function ($q) {
$q->where('status', 'good');
})->count();
$items_status['broken'] = Item::with('latestHistory')->whereHas('latestHistory', function ($q) {
$q->where('status', 'broken');
})->count();
dd($items_status);
i guess you mean latestOfMany() ?
//Item.php
public function latestHistory() {
return $this->hasOne(History::class)->latestOfMany();
}
Also do you have any solution for count the items that doesn't have
history?
Check docs for doesntHave
$items_status['no_history'] = Item::doesntHave('history')->count();

Laravel relationship return null

I have a store that is using a payment package
Now I want to show the items that were purchased, but I run into this problem
Controller
public function mycourse()
{
$courses = PurchasedCourse::where('user_id', Auth::id())
->with('course')
->get();
dd($courses);
return view('student.courses.mycourse', [
'courses' => $courses
]);
}
Model
public function course()
{
return $this->belongsTo(Course::class, 'id');
}
Migration
public function up()
{
Schema::create('courses', function (Blueprint $table) {
$table->id('id');
$table->string('name')->unique();
$table->string('start');
$table->string('end');
$table->integer('price');
$table->string('jalasat');
$table->string('zarfiat');
$table->text('tozih');
$table->integer('hit');
$table->string('department');
$table->string('thumbnail');
$table->tinyInteger('status')->default(0);
$table->string('slug')->unique();
$table->timestamps();
});
}
Your relationship method is wrong. The syntax for the belongsTo() method is
belongsTo(class, ?foreign_id, ?related_id). In your case, it should be:
public function course()
{
return $this->belongsTo(Course::class, 'course_id', 'id');
}
or just
public function course()
{
return $this->belongsTo(Course::class);
}
since your columns follow Laravel's naming conventions.

Laravel paginate polymorphic relationship, topic->comments()

I'm building a basic forum, there are many topics and each topic has comments, a comment or "commentable" can be a a comment or a reply (commented a comment), this is because I want to have nested comments, that's where parent_id is useful. I'm wondering if my polymorphic relationship is the best way to achieve this so I'm open to any suggestions. The first issue I came up with is I don't know hw to do ajax pagination of topic->comments ..., I thought with something like Comment::whereHas('topic') ... but my comments dont' have a topic relationship defined in the model.
I'm using laravel advanced ajax pagination, how can I paginate comments?
Topic model:
class Topic extends Model
{
protected $table = 'topics';
public function author()
{
return $this->belongsTo('App\Models\User', 'user_id');
}
public function comments()
{
return $this->morphMany('App\Models\Comment', 'commentable')->whereNull('parent_id');
}
public function up()
{
Schema::create('topics', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id')->index();
$table->foreign('user_id')->references('id')->on('users');
$table->string('title');
$table->text('body');
$table->string('url')->unique();
$table->string('slug')->unique();
$table->boolean('isVisible')->default(false);
$table->timestamps();
});
}
}
Comment model:
class Comment extends Model
{
protected $table = 'comments';
public function author()
{
return $this->belongsTo('App\Models\User', 'user_id');
}
public function replies()
{
return $this->hasMany('App\Models\Comment', 'parent_id');
}
}
public function up()
{
Schema::create('comments', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id')->unsigned();
$table->integer('parent_id')->unsigned();
$table->integer('commentable_id')->unsigned();
$table->string('commentable_type');
$table->text('body');
$table->timestamps();
});
}
This is where I took inspiration:

Laravel related model attributes are empty?

I'm trying to give ability on user to see his orders. I have created relationships but when i (dd) the result of the function, the related model attributes are empty.
I don't know what is wrong.
Here is my buyer function
//Buyer Orders
public function myOrders()
{
$user = User::find(auth()->user()->id);
$user = $user->products();
dd($user);// related model attributes shows empty
return view('myOrders')->with(compact('user'));
}
and here is my user
public function products()
{
return $this->hasMany(Products_model::class);
}
public function orders()
{
return $this->hasMany(Order::class);
}
public function allOrdersBuyerSeller()
{
return $this->hasMany(OrderProduct::class);
}
products_model
public function orders()
{
return $this->belongsToMany('App\Order', 'order_product');
}
public function user()
{
return $this->belongsTo('App\User');
}
User Migration
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
Product Migration
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('pro_name');
$table->integer('pro_price');
$table->text('pro_info');
$table->integer('stock');
$table->integer('category_id');
$table->string('image')->nullable();
$table->timestamps();
$table->bigInteger('seller_id')->unsigned()->index();
$table->foreign('seller_id')->references('id')->on('users')->onDelete('cascade');
});
}
I would like to see the attributes of the table like price, name, info, img and etc.
Barring the comments about your code, the reason you're not seeing the result of your products query is that you're not passing a closure to the query.
$user = $user->products();
Currently, $user is a QueryBuilder instance. Until you use a closure, like first(), get(), paginate(), etc, you won't be able to see the rows. Modify your code to the following:
$products = $user->products;
// OR
$products = $user->products()->get();
If you omit the (), it will load the relationship using products()->get(), unless already loaded.
Edit: You likely need to include foreign keys to your relationships as the Model name won't match:
User.php
public function products(){
return $this->hasMany(Product_model::class, "seller_id", "id");
}
Probably best to review the contents of the documentation for Relationships; https://laravel.com/docs/5.8/eloquent-relationships. There's a lot of incorrect practices going on with your naming, querying, etc.

How to create follower relationships using Eloquent and Laravel?

So, I'm trying to create a relationship where users can follow other users or follow categories.
My intuition says that what I've done so far is not the right way of doing things. I'm especially confounded by how to create the follower - followee relationship.
TABLES:
Users
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('email');
$table->string('password');
$table->string('first_name');
});
}
Categories
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('category');
});
}
Follows
public function up()
{
Schema::create('follows', function (Blueprint $table) {
$table->increments('id');
$table->integer('follower_id');
$table->integer('followee_id')->nullable();
$table->integer('category_id')->nullable();
});
}
MODELS:
User
class User extends Model implements Authenticatable
{
public function follows()
{
return $this->hasMany('App\Follow');
}
}
Category
class Category extends Model
{
public function follows()
{
return $this->hasMany('App\Follow');
}
}
Follow
class Follow extends Model
{
public function post()
{
return $this->belongsTo('App\User');
}
public function source()
{
return $this->belongsTo('App\Category');
}
}
According to your scenario, it is recommended that you use Polymorphic Many To Many relationship.
Schema:
users
id - integer
...
categories
id - integer
...
followables
user_id - integer
followable_id - integer
followable_type - string
Models:
User:
public function followers()
{
return $this->morphToMany(User::class, 'followables');
}
public function following()
{
return $this->morphedByMany(User::class, 'followables');
}
Category:
public function followers()
{
return $this->morphToMany(User::class, 'followables');
}
Then you can create the relationship like:
When following an User:
$user->followers()->create(['user_id' => 12])
When following a Category:
$category->followers()->create(['user_id' => 25])
Hope it helps.

Categories