How to get hasOne property inside view? - php

How can I echo category name when in Urls view? I get this error:
Column not found: 1054 Unknown column 'categories.url_id' in 'where clause'
(SQL: select * from `categories` where `categories`.`url_id` = 23 and `categories`.`url_id` is not null limit 1
I believe the query should be something like this
SELECT * FROM categories WHERE categories.id = 1
Urls table
id | url | category_id
1 www.asdf.com 1
Categories table
id | category
1 Something
Migration for adding column Category_id to Urls table
public function up()
{
Schema::table('urls', function(Blueprint $table){
$table->integer('category_id')->unsigned()->nullable();
$table->foreign('category_id')->references('id')->on('urls');
});
}
(hm I believe I need to fix this and put references('id')->on('categories') )
Url model
class Url extends Model
{
protected $table = 'urls';
public function category()
{
return $this->hasOne('App\Category');
}
}
Url index controller
$urls = URL::paginate(100)
return view('urls.index')->with('urls', $urls);
Urls.index view
{{ $url->category->category }}
If I change Url model to this
public function category()
{
return $this->belongsTo('App\Category');
}
and when I do var_dump($url->category), the correct SQL query is generated:
select * from `categories` where `categories`.`id` = '1' limit 1
but I still can't get column name with {{ $url->category->category }}
because error is Trying to get property of non-object

Use belongsTo() relationship instead of hasOne():
public function category()
{
return $this->belongsTo('App\Category');
}

Related

Why is the request not working correctly when using BelongsToMany Laravel?

I have 2 models in my app, 'Subject' & 'Professor' (each Subject belongs to many Professors).
I made the many-to-many relation between two model using belongsToMany(). belongsToMany() doesn't work.
I'm trying to get data like this:
$subjects = Subject::with(["professors"])->whereHas("professors", function ($q){ $q->where("id", \request("professor_id")); })->get();
Error:
"SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous (SQL: select * from `subjects` where exists (select * from `professors` inner join `subjects_of_professor` on `professors`.`id` = `subjects_of_professor`.`professor_id` where `subjects`.`id` = `subjects_of_professor`.`subject_id` and `id` = 39))",
Does anyone know where did I make a mistake?
Here's the code to Models:
class Subject extends Model
{
public function professors(): BelongsToMany
{
return $this->belongsToMany(Professor::class, "subjects_of_professor");
}
}
class Professor extends Model
{
public function subjects(): BelongsToMany
{
return $this->belongsToMany(Subject::class, "subjects_of_professor");
}
}
And here is my database structure:
subjects:
id
title
subjects_of_professor:
id
subject_id
professor_id
professors:
id
name
description
I'm found mistake, i was needed to add table in my code, when i trying to get data:
$subjects = Subject::whereHas("professors", function ($q){ $q->where("professors.id", \request("professor_id")); })->get();

laravel querying many to many

I have 2 models, Service and Category. They are related with a many-to-many relationship like so:
Service.php
public function categories()
{
return $this->belongsToMany('App\Category')->withTimestamps();
}
Category.php
public function services()
{
return $this->belongsToMany('App\Service')->withTimestamps();
}
And of course they're joined by a pivot table:
category_service
- category_id
- service_id
- created_at
- updated_at
I'd like to use local scope to filter service result based on IDs of categories. I've done the following:
Service.php
public function scopeFilter($query, $category_ids)
{
$services = Service::whereHas('categories', function (Builder $query) use ($category_ids) {
$query->whereIn('category_id', $category_ids)->get();
});
return $services;
}
But I'm getting a Column not found error, specifically:
Column not found: 1054 Unknown column 'services.id' in 'where clause' (SQL: select * from `categories` inner join `category_service` on `categories`.`id` = `category_service`.`category_id` where `services`.`id` = `category_service`.`service_id` and `category_id` in (1, 2))
1 and 2 are the category IDs I pass.
I wrote the function based on the answer I found here and here.
Any pointers?
Your error message show that your query is begin with categories and without join services.
So put the ->get() outside the closure.
public function scopeFilter($query, $category_ids)
{
$services = Service::whereHas('categories', function (Builder $query) use ($category_ids) {
$query->whereIn('category_id', $category_ids);
})->get();
return $services;
}

How to query a customize key in Laravel?

Considering this tables: person and employee to which connected to person by person_id. This person_id is also the Primary & Foreign key of employee table. Thus in my migrations, i have this:
Schema::create('employees', function (Blueprint $table) {
$table->bigIncrements('person_id');
$table->foreign('person_id')->references('id')->on('persons')->onDelete('cascade');
});
and my show method is like this one
public function show(Employee $employee){
dd($employee->person_id);
$employee = Employee::where('person_id', $employee->person_id)->orderBy('employee_number', 'asc')->join('persons', 'employees.person_id', '=', 'persons.id')->first();
return view('employee.show', compact('employee'));
}
But i am experiencing this issue:
Illuminate\Database\QueryException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select * from `employees` where `id` = 5 limit 1)
Does the query is not aware of the column i am using?
Change the primary key in the Employee model
class Employee extends Model
{
/**
* The primary key associated with the table.
*
* #var string
*/
protected $primaryKey = 'person_id';
public function person()
{
return $this->belongsTo('App\Employee', 'person_id', 'person_id');
}
}
Then query using find
Employee::find($employee->person_id)->with('person')->first();
orderBy and first are redundant on one result queries
And if you want to return the Employee with the Person, just access the relationship object (employee is returned from route model binding)
public function show(Employee $employee) {
$person = $employee->person;
return view('employee.show', compact('employee', 'person'));
}
Hope this helps

Getting to use Eloquent hasMany() relationship

I have a table of categories in which my categories and their title and thumbnails are stored.
I have another table in which images are stored.
The third table is a joint table. I store in each record of it, the id of the image and the id of the category.
Table Schema:
id
cat_id
item_id
Now I want to get a cat_id by query_string and then pass it to the function for it to get the list of all images with this category in the database.
I'm confused about how to write the method. I have written the following method for CategoryList model which throws error:
class CategoryList extends Eloquent
{
protected $table = "categories_list";
function Images ()
{
return $this->hasMany("Image", 'id');
}
}
And here is the usage in the Image model:
return CategoryList::Images()->where("cat_id", '=', $catid)->get()->toArray();
But it throws the following error:
{"error":{"type":"Illuminate\\Database\\QueryException","message":"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'cat_id' in 'where clause' (SQL: select * from `images` where `images`.`id` is null and `cat_id` = 19)","file":"C:\\wamp\\www\\aone\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Connection.php","line":539}}
class Category extends Eloquent {
public function images()
{
return $this->belongsToMany('Image');
}
}
Then do:
$images= Categorie::find($catid)->images;
In this case, your pivot table is 'category_image', but if you need to choose another name, it must be specified
return $this->belongsToMany('Image', 'your_pivot_table_name', 'cat_id', 'item_id');
Please visit http://laravel.com/docs/eloquent#many-to-many for more information

Left join with Where in Eloquent ORM

I'm trying to write this SQL query with Eloquent ORM but still no success:
SELECT *
FROM article
LEFT JOIN article_category
ON article.category_id = article_category.id
WHERE article_category.name_url = 'html'
LIMIT 10`
This is what I've came up with so far (I try to write it with only one query just like above):
ArticleCategory::where('name_url', '=', 'html')->with('articles')->get();
But it shows an error:
Column not found:
1054 Unknown column 'article.article_category_id' in 'where clause'
(SQL: select * from `article` where `article`.`article_category_id` in (1))
My models:
class Article extends Eloquent {
protected $table = 'article';
public function categories() {
return $this->belongsTo('ArticleCategory', 'category_id');
}
}
class ArticleCategory extends Eloquent {
protected $table = 'article_category';
public function articles() {
return $this->hasMany('Article');
}
}
You can change your relationship function to use the correct ID.
public function articles() {
return $this->hasMany('Article', 'category_id');
}
It expects the column category_id to actually be named article_category_id. It expects this because it is referencing the table artice_catigory, so article_category_id makes sense.
If possible, just rename your column in the table article to article_category_id and everything should be good.
You can use left join using eloquent orm as follows
Article::leftJoin('article_category', 'article.category_id', '=', 'article_category.id')
->select(['*'])->where('article_category.name_url','html')->take(10)->get();

Categories