I'm trying to fetch some data from a table called "category", but laravel is throwing the
"SQLSTATE[42S02]: Base table or view not found" error.
I've tried with other table names like "company" and it works perfectly. Both of these tables exist but one of them can not be found with the same code.
This throws the error:
public static function getCategories()
{
$categories = [];
$cat = DB::table('category')->get();
if (isset($cat)){
foreach ($cat as $category_name){
array_push($categories, $category_name);
}
return json_encode($categories);
}
return null;
}
This works as expected (same code except for the table name string):
public static function getCategories()
{
$categories = [];
$cat = DB::table('company')->get(); //table name changed
if (isset($cat)){
foreach ($cat as $category_name){
array_push($categories, $category_name);
}
return json_encode($categories);
}
return null;
}
The only difference between those two tables is table collation:
company: utf8_general_ci
category: utf8mb4_swedish_ci
Create a model if it you don't have one. Add the following into your category model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $table = 'category';
}
Controller
public static function getCategories()
{
$categories = [];
$cat = Category::all();
if (isset($cat)){
foreach ($cat as $category_name){
array_push($categories, $category_name);
}
return json_encode($categories);
}
return null;
}
You're currently using Query Builder, try use eloquent way.
Ok, I found out we had two separate database-servers with almost identical data in them. Both had databases and tables with the same names, but one was missing the category table.
Of course I was connected to the wrong server from laravel after all.
TL;DR: Simple user error in configuration.
Related
Hey so im realively new to Laravel and im having trouble getting related data from my database. I currently have a few tables related to an overarching Product Family table. I currently get the Product Family, and im trying to get the product codes of the products within that family. The problem is im only returning a single product and not a collection. I know im not getting the information correctly and im stuck. My controller currently looks like this
public function getProductFamily($id)
{
$productfamily = ProductFamilyModel::where('id', $id)->first();
$productskus = ProductModel::where('product_family_id', $id)->get();
foreach ($productskus as $products){
$products->product_family()->get();
}
return view('product_page', compact('productfamily', 'products'));
}
I have models setup for both
Product Family:
public function product()
{
// return $this->hasMany(ProductModel::class, 'product_family_id');
return $this->hasMany(ProductModel::class, 'product_family_products', 'product_family_id', 'product_guid');
}
Product:
public function product_family()
{
return $this->belongsToMany(ProductFamilyModel::class, 'product_family_products', 'product_guid', 'product_family_id');
// return $this->belongsTo(ProductFamilyModel::class);
}
Try this:
public function getProductFamily($id)
{
$productfamily = ProductFamilyModel::where('id', $id)->first();
$products = ProductModel::where('product_family_id', $productfamily->id)->get();
return view('product_page', compact('productfamily', 'products'));
}
I am new to make join tables with Eloquent. I want to join 3 tables. But it shows me error. What's my mistake, if anyone notice it will be helpful for me. Here is tables....
In 1st table Applications(id,u_id,program_name) 2nd table StudentInfos(id,u_id,.....) 3rd table users(id,.....)
in Application model
public function StudentInfo()
{
return $this->hasOne('App\StudentInfo', 'u_id', 'u_id');
}
in StudentInfo model
public function User()
{
return $this->hasOne('App\user', 'u_id', 'id');
}
From controller
public function view_application($id)
{
$vu_data = Application::where('id', $id)->get();
$vu_data2 = $vu_data->StudentInfo()->get();
return $vu_data2;
}
$vu_data2 = $vu_data->StudentInfo()->get();
is returning a collection and not just a single Application Model. Change "get()" to "first()", and this will fix your first error. So change:
$vu_data = Application::where('id', $id)->get();
to
$vu_data = Application::where('id', $id)->first();
When you do get(), it returns a collection. You can do :
$vu_data = Application::findOrFail($id);
$student = $vu_data->StudentInfo;
$user = $student->User;
I'm pretty new to Laravel and i got stuck with building a more complex query:
I've 3 tables with their models:
Codes:
id
description
factor
public function purposes() {
return $this->hasMany('App\Purpose', 'code_purposes', 'code_id', 'purpose_id');
//I could be wrong here
}
Purpose:
id
name
description
Code_purposes:
code_id
purpose_id
public function codes() {
$this->belongsToMany('App\Code'); //I could be wrong here
}
public function purposes() {
$this->belongsToMany('App\Purpose'); //I could be wrong here
}
What I want is to fetch all the codes with the condition where the purposes name = 'some_name'
I thought this would be easy with the relationships, but I can't figure it out.
So how do I do this in Laravel?
In Code model:
public function purposes() {
return $this->belongsToMany('App\Purpose');
}
In Purpose model:
public function codes() {
return $this->belongsToMany('App\Code');
}
Now you can get data like:
$codes = Purpose::where('name', 'some_name')->first()->codes;
Relation table name must be code_purpose. And no need any model for this table.
Source: Laravel Many To Many Relationships
My tables
Modelos
id
nome slug
marca_id
Pecas
id
codigo
modelo_peca
modelo_id
peca_id
produtos
id
categoria_id
codigo
nome
categorias
id
nome
slug
I have these models
class Modelo extends Eloquent
{
public function pecas()
{
return $this->belongsToMany('Peca');
}
}
class Peca extends Eloquent {
public function modelos()
{
return $this->belongsToMany('Modelo');
}
public function produtos()
{
return $this->belongsToMany('Produto');
}
}
class Produto extends Eloquent {
public function pecas()
{
return $this->belongsToMany('Peca');
}
}
I´m trying to create a route that pass all the products related to a modelo to a view. What´s wrong?
Route::get('/modelo/{slug?}', function($slug = null) {
if ($slug) {
$id = Modelo::where('slug', $slug)->pluck('id');
$pecas = Modelo::find($id)->pecas;
$produtos = Peca::where('id', $pecas)->get();
}
return View::make('produto.home')->with('produtos', $produtos);
Use eager loading
Off the top of my head (also across the language barrier I'll do my best)
You seem to want all Products (produtos) for a specific page category other taxonomy (may be wrong but you can adjust the code as needed)
The where() method expects three parameters iirc so instead the first query would be $id = Modelo::where('slug', '=', $slug)->pluck('id');
The same would apply to the other where statements.
Full query:
if($slug)
{
$query = Modelo::with('pecas.produto')
->where('slug', '=', $slug)
->get();
$produtos = $query->produto;
}
return View::make('produto.home')->with('produtos', $produtos);
Here I've taken a different approach and eager loaded the relations, I'm not 100 percent sure this is how you want this to be done but it hopefully gives you a foundation for using your relations properly in Eloquent.
You don't need to manually get primary keys and perform multiple queries, check out the Eloquent documentation on the Laravel website.
I have two tables, organizations and categories. This is how my tables and models are set up:
Tables:
organizations
id - integer
category_id - integer, fk
name - string
...
categories
id - integer
name - string
Models:
class Organization extends Eloquent
{
public function category()
{
return $this->belongsTo('Category');
}
public function comments()
{
return $this->morphMany('Comment', 'commentable');
}
}
class Category extends Eloquent
{
public $timestamps = false;
public function organization()
{
return $this->hasMany('Organization');
}
}
In my routes.php file, I have the following code (where $category is equal to "organizations"):
$query = Organization::query()
->join('categories', 'categories.id', '=', $category . '.id')
->select('categories.name as category');
$tiles = $query->get();
In my view, I am able to perform the following actions without any errors:
foreach($tile->comments as $comment)
{
...
}
...
$tile->name;
However, calling $tile->category->name will give me the error Trying to get property of non-object. And calling $tile->category will just return null. How can I display the category associated with the organization? I am able to retrieve other properties and relations just fine, but this is giving me a problem.
You have a bug in your code: $category . '.id' should be $category . '.category_id' doing so should make $tile->category->name work.
Also please note (you probably already know this) that in the code that you provided you are not actually using the belongsTo relation as set in your Organization class, you are just using the joined data.
The following would also work using the Eloquent ORM utilizing the models relationship methods:
$tiles = Organization::with('category')
->get();
foreach ($tiles as $tile)
{
echo $tile->name . '<br>';
echo $tile->category->name . '<br>';
}
Or you could do so the other way round from the categories model like so:
$tiles = Category::with('organization')
->get();
foreach ($tiles as $tile)
{
echo $tile->name . '<br>';
foreach($tile->organization as $org)
{
echo $org->name . '<br>';
}
}