May be is something very easy but as I'm really new in Laravel and MVC frameworks can't figured it out.
Currently the source which I have showing products on the home page. Now I want to put WHERE clause in the query ... but I can't find the query.. What I have in HomeController.php is
public function index()
{
$products = Product::paginate(15);
return View::make('site.index', [
'products' => $products
]);
}
In the models/Product.php this
class Product extends Eloquent {
protected $table = 'products';
protected $primaryKey = 'product_id';
public $timestamps = false;
}
Where exactly I should put WHERE cat_id = 1...
You need to write,
$products = Product::where('cat_id','=','1')->paginate(15);
Please refer this link also.
Hope it will help you :-)
Related
:)
I've a problem with a relationship in my project, this is the situation, I have two models "Sucursales" and "Checklist", this is the logic... one sucursal can have many checklist, but is one request I only need to get the most recent sucursal's checklist... the simple relation works fine when I call it, but when I'm trying to get the most recent checklist the result is empty, here is the code:
Sucursales Model
class Sucursales extends Model
{
protected $table = 'db_sucursales';
protected $primaryKey = 'id_sucursal';
protected $fillable =['tipo_sucursal', 'no_sucursal', 'id_gcb', 'id_coordinacion', 'nombre_sucursal', 'id_estado', 'direccion_sucursal', 'telefono_sucursal', 'id_estatus'];
public $timestamps = false;
public function checkslist(){
return $this->hasMany(ChecklistSucursal::class, 'id_sucursal','id_sucursal');
}
}
Checklist model:
class ChecklistSucursal extends Model
{
protected $table = 'db_checklist_sucursales';
protected $primaryKey = 'id_checklist';
protected $fillable = [
'folio', 'id_sucursal', 'id_usuario', 'nombre_aplicador', 'encargado_sucursal', 'puesto_encargado_sucursal', 'fecha_aplicacion', 'checklist','estatus','comentarios'
];
public function sucursal(){
return $this->hasOne(Sucursales::class, 'id_sucursal', 'id_sucursal');
}
}
When I call:
$sucursales = Sucursales::with('checkslist')->orderBy('no_sucursal', 'asc')->get();
works fine, but when I call the next code:
$sucursales = Sucursales::with(['checkslist' => function($query){
return $query->latest('fecha_aplicacion');
}])
->orderBy('no_sucursal', 'asc')
->get();
the result is empty...
Please someone can tell me what I'm doing wrong, this project is in laravel 5.5
i have 2 models. PostModel and CategoriesModel.
class PostModel extends Model
{
protected $table='posts';
protected $primaryKey = 'id';
protected $guarded=['id'];
public function categories()
{
return $this->belongsTo(CategoriesModel::class);
}
}
class CategoriesModelextends Model
{
protected $table='categories';
protected $primaryKey = 'id';
protected $guarded=['id'];
public function posts()
{
return $this->hasMany(PostModel::class);
}
}
I want to get 6 categories with 10 posts.
I used this code in my controller
$categories = CategoriesModel::with(['pages' => function($query) {
$query->limit('10');
}])->take("6")->get();
but this code is wrong. it applies to all records. But the truth is that this query applies per one categories. please help me.thanks
there is a laravel package specialized in this called Eloquent Eager Limit:
after installing it:
composer require staudenmeir/eloquent-eager-limit:"^1.0"
you should use it inside the models that would apply limited eager loading:
class PostModel extends Model
{
use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
// ........
}
class CategoriesModel
extends Model
{
use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
// ........
}
now this query will get the result you want:
$categories = CategoriesModel::with(['pages' => function($query) {
$query->limit('10');
}])->take("6")->get();
For eager loading you can do like this with map operation :
$categories = CategoriesModel::with('pages')->take(6)->get()
->map(function($q)
{ $q->pages = $q->pages->take(10); // take only 10 query
return $q;
}
);
The reason the above approach is necessary is because the constrained eager loading query roughly translates to SQL like:
Query to select Categories:
select * from `categories`
limit 6;
Query to fetch relation
select * from `categories`
inner join `posts` on `categories`.`id` = `posts`.`category_id`
where `posts`.`category_id` in (id's from categories query)
limit 10;
First of all your relation name is wrong in your controller. Update your category model by the following code:
public function ten_posts()
{
return $this->hasMany(PostModel::class)->take(10);
}
then update your controller with the following code:
$categories = CategoriesModel::with('ten_posts')->take(6)->get();
Try like this -
$categories = CategoriesModel::with(['pages' => function($query) {
$query->take('10');
}])->take("6")->get();
I want to get the data from pdf_Files table where it will only show the name of files based on it user_id. I don't really know how to explain it but maybe if you see my codes, you would understand. I have already finish making the relationship between this 2 tables already
I want it to be something like:
DB::table('pdf_files')->where(table:personal_infos->id = pdf_files->user_id)->get(); --> I want it to be something like that but I do not know how to get it
Here is my code:
Controller:
public function downfunc(Request $request){
$downloads=DB::table('pdf_files')->get();
return view('download.viewfile',compact('downloads'));
}
pdfFile model:
protected $fillable = array('file_name','file_size','user_id');
public function personal_infos() {
return $this->belongsTo('App\personal_info', 'user_id', 'id');
}
personal_info model:
class personal_info extends Eloquent
{
protected $fillable = array('Email', 'Name');
protected $table = 'personal_infos';
protected $primaryKey = 'id';
public function pdfFiles() {
return $this->hasMany('App\pdfFile','user_id');
}
}
Are you going to search multiple user ids at once or are you getting the id from the request?
If you are getting the info from the request, you would want to do something like this:
use App\pdfFile; //Put this above the class
pdfFile::where('user_id', $request->user_id)->get(); //If you are checking to see if something equals something else in eloquent, you do not have to use equals
I have a simple code, and now I want to select data from 2 tables. Then I want to show in my view. Here's my code
model:
Tikpro.php
class Tikpro extends Model {
public $table = "TIKPRO";
public $primaryKey = "ID_TIKPRO";
public function permintaan() {
return $this->hasMany('Permintaan', 'TIKPRO_ID', 'ID_TIKPRO');
}
model:
Permintaan.php
class Permintaan extends Model {
public $table = "PERMINTAAN";
public $fillable = array(
'NOMOR_TICKET',
'TGL_PERMINTAAN',
'NAMA_REQUESTER',
'BARANG_PERMINTAAN',
'NO_FPBJ',
'TGL_INPUT_FPBJ',
'TARGET_SELESAI',
'KETERANGAN',
'TINDAK_LANJUT_AKHIR',
'STATUS',
'FPB',
'RFQ',
'DO',
'BAST',
'TGL_DEADLINE',
'titik_proses',
'TIKPRO_ID',
);
public $primaryKey = "ID_PERMINTAAN";
public function tikpro() {
return $this->belongsTo('Tikpro','TIKPRO_ID','ID_TIKPRO');
}
Controller:
PermintaanController.php
public function details($ID_PERMINTAAN) {
$query = DB::table('PERMINTAAN')->select('TIKPRO.NAMA_TIKPRO')->join('TIKPRO','TIKPRO.ID_TIKPRO','=','PERMINTAAN.TIKPRO_ID')->get('all');
$jebret = Permintaan::find($ID_PERMINTAAN);
return view('permintaan.details', compact('jebret'))->with($query);
}
And how can I show it? In my view I try {{ $jebret->$query }} . But still can't show the data.
How should I write code? Thanks
I think you can try this
public function details($ID_PERMINTAAN) {
$query = DB::table('PERMINTAAN')->select('TIKPRO.NAMA_TIKPRO')->join('TIKPRO','TIKPRO.ID_TIKPRO','=','PERMINTAAN.TIKPRO_ID')->where('PERMINTAAN.ID_PERMINTAAN',$ID_PERMINTAAN)->get();
return view('permintaan.details', compact('query'));
}
Hope this work for you
There's 2 ways here. The first and easiest (if you've set it up correctly) is the relationship. https://laravel.com/docs/5.4/eloquent-relationships. To use the one in your example you want to do this:
$permintaans = Permintaan::query()->get()->all();
return view('permintaan.details', [
'permintaans' => $permintaans,
]);
//In the view
#foreach($permintaans as $permintaan)
<tr>{{$permintaan->tikpro->attribute}}</tr>
#endforeach
Another way like you've attempted is the join. In the select though I would leave it blank so you get all columns!
$permintaans = Permintaan::query()
->join('TIKPRO','TIKPRO.ID_TIKPRO','=','PERMINTAAN.TIKPRO_ID')
->get()
->all();
I'm trying to return nested JSON response, need to connect multiple tables, but for now, I'm just trying with 3, the levels can go deeper. My models are following:
Update #1:
class Sport extends Eloquent {
protected $table = 'sportovi';
protected $fillable = ['id', 'sport_eng'];
public $timestamps = false;
public function liga(){
return $this->hasMany('League', 'sport_id');
}
}
class League extends Eloquent {
protected $table = 'lige';
protected $fillable = ['league_id', 'liga', 'sport_id'];
public $timestamps = true;
public function mec(){
return $this->hasMany('Match', 'match_id');
}
}
class Match extends Eloquent {
protected $table = 'mecevi';
protected $fillable = ['match_id', 'home', 'away', 'kotime', 'day', 'kolo', 'sport_id', 'league_id', 'date', 'long_id'];
public $timestamps = false;
public function liga(){
return $this->belongsTo('Match', 'league_id');
}
}
If I do:
$sportovi = Sport::with('liga')->get();
return $sportovi;
everything is normal, children of "lige" are nested where they should be, as shown on the link here, but, if I try to add the Match, like this:
$mecevi = Sport::with('liga.mec')->get();
I get a "mec" node, which is an empty array, as shown here, instead going one level deeper, like in the previous example.
I've also tried making multiple with() conditions which throws an error
Call to undefined method Illuminate\Database\Query\Builder::mec()
Update: Still the same, mec:[], empty array.
I'm using Laravel 4.2.
From my understanding, you want to get all the matches of leagues
The problem might be in the second parameter in hasMany function
public function mec(){
return $this->hasMany('Match', 'league_id');
}
The second parameter need to be foreign_key
public function mec(){
return $this->hasMany('Match', 'match_id', 'league_id');
}
source: http://laravel.com/docs/4.2/eloquent#one-to-many
Figured it out, my table relations were off, after giving all the conditions, like
return $this->hasMany('Comment', 'foreign_key', 'local_key'); everything started working as it should. Thanks everybody.