Eloquent ORM One to many query is not working - eloquent

I am working with laravel 5.4. I have created countries and states table.
countries table looks like below
And my states table is :
Here, I have written join query as shown in below. It works perfect.
$state = DB::table($this->tbl_states)
->join($this->tbl_countries, $this->tbl_countries.'.id', '=', $this->tbl_states.'.country_id')
->select($this->tbl_states.'.*', $this->tbl_countries.'.name as country_name')
->whereNull($this->tbl_states.'.deleted_at')
->paginate(10)
But, Instead of writing this query I want to use Eloquent ORM so what query should I have to write?
In Country model I have create function that looks like below :
public function states()
{
return $this->hasMany('state');
}
And in State model I have write function that looks like below :
public function country()
{
return $this->hasOne('country');
}

In Country model try this:
public function states()
{
return $this->hasMany(App\State::class);
}
And in State model:
public function country()
{
return $this->belongsTo(App\Country::class);
}
And then $country->states will give you all states of this country. As well as $state->country will return state's country.
Official Docs: Eloquent: Relationships

Related

Laravel eloquant belongsToMany get records belongs to relationship

I'm using many to many relationship with products and product_categories tables using product_product_category pivot table.
Product model
class Product extends Model
{
public function product_categories() {
return $this->belongsToMany(ProductCategory::class, 'product_product_category');
}
}
ProductCategory model
class ProductCategory extends Model {
public function products() {
return $this->belongsToMany(Product::class, 'product_product_category');
}
}
What I need to do is when I supply an array of categories need to get products only with these categories. This is my code
$selectedCategotries = array(1, 2);
$products = Product::with(['product_categories' => function($q) use ($selectedCategotries){
$q->whereIn('product_categories.id', $selectedCategotries);
}])->get();
But I get all the products instead. It will be a great help if you can supply a solution for me.
Finally, I found an answer with whereHas. Adding the answer for anyone who come up with the same issue.
$products = Product::whereHas('product_categories', function ($q) use ($selectedCategotries) {
$q->whereIn('product_categories.id', $selectedCategotries);
})->get();

how to join 3 table in laravel using database mongodb?

Our Application has 3 Model "Notification", "Postlike" and "Post"
In Notification Model:
public function postlike()
{
return $this->belongsTo('App\Models\PostLikes', 'postlist');
}
public function post()
{
return $this->hasMany('App\Models\PostLikes', '_id', 'c_post_id');
}
In Postlike Model:
public function postlist()
{
return $this->hasMany('App\Models\Post', '_id', 'c_post_id');
}
In Notification Repository: (Query)
public function getnotification($userId)
{
$notification = $this->makeModel()
->with('post')
->with('postlike')
->with('notification')
->orderBy('created_at' , 'desc')
->where('replied_id', $userId)
->get();
return $notification;
}
For more information we have attached following Image
enter image description here
When i firt saw your post, i thought your problem could be solved using Laravel's built-in eager loading, so it lets you do something like this:
$notification = $this->makeModel()
->with('post', 'postlike', 'postlike.postlist')
//...
->get();
If thats your case, these links shoud do the trick:
https://laracasts.com/discuss/channels/eloquent/eager-load-multiple-nested-relationships
laravel eloquent eager load multiple nested relationships
Im not sure, but it seems a little bit odd to me, that 'Notification' Model has two relations with 'Postlike' model. Maybe you should consider using some pivot table.
Hope it helps,
Notification Model :
public function postlike()
{
return $this->belongsTo('App\Models\PostLikes', 'c_post_id');
}
Query:
$notification = $this->makeModel()
{
->with('post', 'postlike', 'postlike.postlist')->get()
}

eloquent refer to a column of a related a model

I have three tables:
categories
id, title
products
id, name
categories_products
id, category_id, product_id
I have also setup the according models and relationships (both have belongsToMany of the other)
Now I want to get all products belonging to a category
Category::where('title','Electronics')->first()->products()->limit(10)->get(['products.name']);
which works fine, but I also want to include the category title for each product as well:
Category::where('title','Electronics')->first()->products()->limit(10)->get(['products.name','category.title']);
However it returns: Column not found category.title
I thought that the relation would take care of it.
EDIT: Models -->
Category:
class Category extends Model
{
protected $fillable = array('title');
public function products()
{
return $this->belongsToMany('Product', 'categories_products', 'category_id', 'product_id');
}
}
class Product extends Model
{
protected $fillable = array('name');
public function categories()
{
return $this->belongsToMany('Category', 'categories_products', 'product_id', 'category_id');
}
}
The reason you're getting the error is because get() works just like select() and because you're running the category query and then running the product query after there is no categories table to reference for the select.
Look into Eager Loading. It will help with a lot of these kinds of issues. Your query can be written as:
Product::select('id', 'name')
->with(['categories' => function($query) {
return $query->select('id', 'title');
}])
->whereHas('categories', function($query) {
return $query->where('title', 'Electronics');
})
->limit(10)
->get();
Because we are lazy loading you NEED the id column on each model so Laravel knows where to attach the relationships after the queries are run.
The with() method above will eager load the categories relationship and the whereHas() method puts a relationship constraint on the current query.
UPDATE
Similar query from Category model:
$category = Category::where('title','Electronics')
->with(['products' => function($query) {
return $query->select('id', 'name')->limit(10);
}])
->first(['id', 'title']);
Then access the products with:
$category->products

Laravel 5.3 Eloquent Relationship 1-1 Query

Hi guys how could I query a data from my database with one-to-one relationship on eloquent model?
I want to query the menus with specific category id.
For example I only want to query the meals with "Breakfast Category".
Menu Model:
public function menucat()
{
return $this->hasOne('App\MenuCat', 'menu_cat_id', 'id');
}
Menu_Cat Model
public function menus()
{
return $this->belongsTo('App\Menu', 'menu_cat_id', 'menu_cat_id');
}
Database Table:
menus Table
id | menu_cat_id | menuName
menu_cat Table
menu_cat_id | menuCatName
I find it easy using the Query builder but I would like to use the eloquent to query out the data I need.
Thanks in Advance!
in the documentation you have that
return $this->hasOne('App\Phone', 'foreign_key', 'local_key');
you need to inverse menu_cat_id and id like that
return $this->hasOne('App\MenuCat', 'id', 'menu_cat_id');

Get Discriminator in Linq Select results

I'm trying to make a SQL Query with LinqToEntities which will be as efficient as possible so I would like to avoid iterating after every record I get in results to get a new corrected collection. I'm trying to create a ready collection to send as a result in API just with this one query.
I'm trying to get a discriminator value though with inherited models.
My models are somewhat like these:
public abstract class DbEntity
{
[NotMapped]
public string DiscriminatorValue
{
get
{
return ObjectContext.GetObjectType(GetType()).Name;
}
}
}
public class Foo : DbEntity {
}
public class Bar: DbEntity {
}
This model will create a table in database which will have a column called Discriminator. To get the discriminator value I used my custom DiscriminatorValue property but it won't work in queries like this:
var events = context.MyTable.Select(t => new {
Discriminator = t.DiscriminatorValue
}).ToList();
This below one will obviously work, but it will be much slower imho:
var events = context.MyTable.ToList().Select(t => new {
Discriminator = t.DiscriminatorValue
}).ToList();
Is it possible to get Discriminator value without having to write my custom SQL query myself (like real sql which I know is possible too).