Laravel - eloquent relation - php

This is meal table:
Id,
Category_Id
This is categories table:
Id,
Slug
How do I define relationship between those 2 (return array Meal with array category inside to get slug)
I tried putting this:
meal.php
function returnCategories()
{
return $this->belongsTo(Category::class);
}
and this doesnt work
Edit:
In Controller file I want to define it like:
Meal::with('returnCategories');
Controller code:
return Meal::select('id')->with('category')->get();

try this
function returnCategories()
{
return $this->belongsTo(Category::class, 'Category_Id', 'Id');
}
or you can try
function category()
{
return $this->belongsTo(Category::class, 'Category_Id', 'Id');
}
and try using select(*). this worked for me.
$meals = Meal::select( '*' )->with('category')->get();

Related

How to get a custom collection based on a data that is most repeated (from top to bottom))

I have a table like this:
Basically this table is named favourite_products and contains product ids that are added as favourite for users.
Now I wanted to get a collection of most added product from this table.
So in this case, a product with an id of 10 would be on top of the collection.
But I don't know how to get this collection ordering by from most repeated product id (prd_id)...
Here is the Model:
class FavouriteProduct extends Model
{
protected $table = 'favourite_products';
protected $fillable = ['usr_id','prd_id'];
public function user()
{
return $this->belongsTo(User::class, 'usr_id');
}
public function product()
{
return $this->belongsTo(Product::class, 'prd_id');
}
}
UPDATE #1:
Product.php Model:
public function favouritees()
{
return $this->belongsToMany(User::class, 'favourite_products', 'prd_id', 'usr_id');
}
I think the following code solve your problem:
$most_liked_products = DB::table('favourite_products')
->select(DB::raw('count(prd_id) as total'), id)
->groupBy('total')
->orderByDesc('total')
->get();
Please try it and give your feedback
try use this
public function example()
{
$data=FavouriteProduct::orderBy('prd_id', 'ASC')->get();
dd($data);
}

Laravel - how to use model's ID inside belongs to many relationship query?

Models:
Products
Variants
VariantValue
// Product.php
public function variants()
{
return $this->belongsToMany(Variant::class, 'product_variant', 'product_id', 'variant_id')
->with([
'values' => function ($builder) {
return $builder->whereHas('products', function ($q) {
return $q->where('products.id', $this->id);
});
},
]);
}
// Variant.php
public function values()
{
return $this->hasMany(VariantValue::class);
}
// VariantValue.php
public function products()
{
return $this->belongsToMany(Product::class, 'product_variant_value', 'variant_value_id', 'product_id');
}
The above works if we do the following:
Product::first()->variants()->get()->toArray()
But, it doe NOT work if we do the following (the values array is empty):
Product::with('variants')->get()->toArray()
Meaning the issue is that the product ID is not available inside the belongs to many query:
return $q->where('products.id', $this->id);
Any idea how I can make this work? The goal is to load relationship using:
Product::with('variants')->get()

How to filter entries via hasMany relationship in Laravel

I'm trying write an website with Laravel (current version is 5.7) and I have 3 models as: Post, User and Fav. I'm using a simple form to add posts to "favs" table which has 3 columns as; id, user_id and post_id. And I want to list posts that user added favorites bu I can't use "hasMany" method properly.
I can use variables like; $post->user->name but I can't figure it out how to use relationship with "favs" table.
Post Model
public function user() {
return $this->belongsTo('App\User');
}
public function favs() {
return $this->hasMany('App\Fav');
}
Fav Model
public function users() {
return $this->hasMany('App\User');
}
public function posts() {
return $this->hasMany('App\Post', 'post_id', 'id');
}
User Model
public function posts() {
return $this->hasMany('App\Post');
}
public function favs() {
return $this->hasMany('App\Fav');
}
Controller
public function user($id){
$favs = Fav::orderBy('post_id', 'desc')->get();
$user = User::find($id);
$posts = Post::orderBy('id', 'desc')->where('user_id', $id)->where('status', '4')->paginate(10);
return view('front.user')->with('user', $user)->with('posts', $posts)->with('favs', $favs);
}
The Fav model only has one User and Post each, so you need to use belongsTo() instead of hasMany and change the method names to singular. You can also remove the additional parameters in post() since they're the default values.
public function user() {
return $this->belongsTo('App\User');
}
public function post() {
return $this->belongsTo('App\Post');
}
Loading all Posts that a user has favorited:
$user->favs()->with('post')->get();
The with() method is used to eager load the relationship.
Now you can loop through the Favs:
#foreach($favs as $fav)
{{ $fav->post->name }}
#endforeach
I think you can change these two lines of your code to
$posts = Post::orderBy('id', 'desc')->where('user_id', $id)->where('status', '4')->paginate(10);
return view('front.user')->with('user', $user)->with('posts', $posts)->with('favs', $favs);
to
$posts = Post::where('user_id', $id)->where('status', '4')->latest()->paginate(10);
return view('front.user', compact('user', 'posts', 'favs'));
And for retrieving favorite posts of an user,
if you will change the fav table to make it a pivot table only to handle a many to many relationships between Post and User, you can get it as $user->posts, for a separate model, I think you can consider something like $user->favs and in view
In Fav model
public function user() {
return $this->belongsTo('App\User');
}
public function post() {
return $this->belongsTo('App\Post');
}
and in view
#foreach ( $user->favs as $fav )
{{ $fav->post->id }}
#endforeach
If an User, per example, have many Favs you need to use a Iteration Block, like foreach.
Example:
foreach($user->favs as $fav) {
dd($fav) // do something
}
Ps.: Be careful not to confuse hasMany and belongsToMany.

Select specific column in laravel eloquent's with method

I am using laravel 5.6 and i want to get user posts with comments (only id field)
User Model
public function posts()
{
return $this->hasMany('App\Post');
}
Post Model
public function user()
{
return $this->belongsTo('App\User');
}
public function comments()
{
return $this->hasMany('App\Comment');
}
Comment Model
public function post()
{
return $this->belongsTo('App\Post');
}
In my controller i am using this code to get user posts with their comments
$posts = $request->user()->posts()->with(['comments' => function($query) {
$query->select(['id']);
}]);
But its not working...
When i comment $query->select(['id']); it works fine but returns Comment model all fields. I want to only select id field.
What i am missing here?
You also have to select the foreign key column (required for matching the results):
$posts = $request->user()->posts()->with('comments:id,post_id');
If you want to only one column, you can use ->pluck('id')
https://laravel.com/docs/5.6/collections#method-pluck

Eloquent WHERE NOT with relationships

I am using Lumen and it's Models with model's relationships. What I am trying to do is to get all Categories and count how many posts every category has, which is working fine. However, I do not want it to count those which creator_id == $current_user_id, how should I do it?
This is in my Post class:
public function user(){
return $this->belongsTo(User::class);
}
public function category(){
return $this->belongsTo(Category::class);
}
And this is in my Category class:
public function posts(){
return $this->hasMany(Post::class);
}
And this is my query:
public function getCategories($user_id){
$categories = Category::withCount('posts')->get();
return new JsonResponse(['categories' => $categories]);
}
So I do not want to count posts that the current user has created.
So the output should be something like this:
{
"categories": [
{
"name": "All",
"posts_count": 0
}]
}
This what I also tried without success:
$categories = Category::where('creator_id', '!=', $user_id)->withCount('posts')->get();
Try using the following line:
$categories = Category::withCount(['posts' => function($query) use($user_id){
$query->where('creator_id', '!=', $user_id);
}])->get();

Categories