I have 3 models: User, Query, Offer. The relation is that user has many queries and query has many offers.
In controller I use $queries=User->query()->get(); (query() is a hasMany method in User model) and pass it to view as parameter. In view I want to display a table of queries from single user and count all offer made to each query.
Actually what I want to get, is a nested object $queries like
user:
query1:
offer1
offer2
query2:
offer3
offer4
How it should be coupled in models and how to use it in controller and view?
You could have something like:
Class User extends Model{
protected $table = 'users';
public function query(){
return $this->hasMany('App\Query');
}
}
Class Query extends Model{
protected $table = 'queries';
public function offer(){
return $this->hasMany('App\Offer');
}
public function user(){
return $this->belongsto('App\User');
}
}
Class Offer extends Model{
protected $table = 'offers';
public function query(){
return $this->belongsTo('App\Query');
}
}
Then in your controller you can have something like this:
public function showUser($id){
$user = User::with('query.offer')->find($id);
return View::make('user')->with('user', $user);
}
Then in your view you could have something like:
#foreach($user->query as $query)
{{$query->title}}
#foreach($query->offer as $offer)
{{$offer->title}}
{{$offer->amount}}
#endforeach
#endforeach
Related
I have table relation like this:
Is it possible to get the data of the project from the cash mutation table?
In example in cash mutation table with id '4' I wanna call agency name from projects table.
I've done it with with (eager loading in Laravel) but it returns null like:
$cash_mutations = CashMutation::where('id', 4)->with('project')->get();
This is my CashMutation Model:
class CashMutation extends Model
{
use HasFactory;
protected $guarded = ['id'];
public function category(){
return $this->belongsTo(Category::class);
}
public function balanceType(){
return $this->belongsTo(BalanceType::class);
}
public function project(){
return $this->belongsTo(Project::class, 'cash_mutation_id', 'id');
}
public function deposit(){
return $this->hasMany(Deposit::class);
}
}
and this is my Project Model:
class Project extends Model
{
use HasFactory;
protected $guarded = ['id'];
public function cashMutation(){
return $this->belongsTo(CashMutation::class);
}
public function projectFunding(){
return $this->hasMany(ProjectFunding::class);
}
public function SharingProfit(){
return $this->hasMany(SharingProfit::class);
}
}
Is it possible to do that in Laravel? If it possible anyone want to tell me about it? Thanks
Yes. It is definitely possible.
You don’t get an error message so the basic configuration should be fine.
I suspect that the data in the database is not correct. What’s the project_id for the CashMutation with the id 4? Is it maybe null?
I'm trying to directly edit my Kodi MySQL DB and build a tool to fix some scraping errors that have always been not quite right.
the relationship of tables is
tvshow -> episode -> file
So I'm able to so far (after creating models for these tables)
List all shows
view specific show and list all episodes
show file entry for that episode.
What I'm trying to do is list all files that belong to the show, via a dropdown. ( as I need to change them )
So I need to use the TVShow model to get all epiodoes that have an idShow entry.. AND then get all the files based on the episode table. I know that Eloquent can handle this typically, but I've only ever used my own table structure, never one like this.. so I think my issue is over riding key names etc...
the key column names are:
idShow
idEpisode
idFile
(Where that SAME name is used as the primary key on the parent table AND the mapping ID in the child table)
Anyhoo, here's my models..
Any ideas?
TVShow
<?php
namespace App\Models;
use Eloquent as Model;
class TvShow extends Model
{
public $table = 'tvshow';
protected $primaryKey = 'idShow';
public function episodes()
{
return $this->hasMany(Episode::class, 'idShow');
}
}
Episode
<?php
namespace App\Models;
use Eloquent as Model;
class Episode extends Model
{
public $table = 'episode';
protected $primaryKey = 'idEpisode';
public function tvshow()
{
return $this->belongsTo(TvShow::class, 'idShow', 'idShow');
}
public function season()
{
return $this->hasOne(Season::class, 'idShow', 'idShow')->where('season', '>=', 0)->where('idSeason', $this->idSeason);
}
public function file()
{
return $this->hasOne(File::class, 'idFile', 'idFile');
}
public function files()
{
return $this->hasMany(File::class, 'idFile', 'idShow');
}
}
File
<?php
namespace App\Models;
use Eloquent as Model;
class File extends Model
{
public $table = 'files';
protected $primaryKey = 'idFile';
public function episode()
{
return $this->belongsTo(Episode::class, 'idFile', 'idFile');
}
}
I'm calling this in my Controller...
TvShow::with('episodes.files')->get();
I'm getting ALL shows as a list..?
A hasManyThrough relationship will work. Add this to your TvShow model.
public function files()
{
return $this->hasManyThrough(Episode::class, File::class);
}
See https://laravel.com/docs/7.x/eloquent-relationships#has-many-through
I try to fetch data from database in codeigniter construct function
but getting undefined method error
controller-
class Welcome extends CI_Controller
function __construct()
{
parent::__construct();
$this->load->model('Login');
$this->Login->getadminnav();
}
}
model-
class Login extends CI_Model
{
public function adminnav()
{
$query="SELECT * from adminnav where status='1'";
$query->row_array();
return true;
}
}
You got to load the model you are using first:
$this->load->model('login_model');
$this->Login->getadminnav();
And remember to rename the model to Login_model
Try these pieces of code.
Controller:
class Welcome extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('Login');
$this->Login->adminnav();
}
}
Model:
class Login extends CI_Model{
public function adminnav(){
$this->load->database();
$sql = "SELECT * from adminnav where status='1'";
$result = $this->db->query($sql);
return $result;
}
}
I am seeing in your code that-
In controller you didn't start the second bracket after controller name.
You defined the function name as "adminnav" in model but called it as "getadminnav" in Controller
You didn't load the database in model (If you already loaded it in autoload.php then here is not needed)
Anyway please let me know whether your problem is solved or not.
you are calling getadminnav() but in your model the method name is adminnav.and change model name Login to Login_model.
try this:
class Welcome extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('Login_model');
$this->Login->adminnav();
}
}
// model
class Login_model extends CI_Model{
public function adminnav()
{
$query="SELECT * from adminnav where status='1'";
$query->row_array();
return true;
}
}
I'm having trouble with a Laravel 5 relationship. I have 2 models Crew and Event with the corresponding tables crews and events. Crews have many events, and events have one crew. I set up my models and migration as follows:
Schema:
//Crews
Schema::connection('scheduling')->create('crews', function ($table) {
$table->increments('id');
$table->text('name');
$table->boolean('solo');
$table->boolean('active');
$table->text('phone');
});
//Events
Schema::connection('scheduling')->create('events', function ($table) {
$table->increments('id');
// ...
$table->integer('crew_id')->unsigned();
$table->foreign('crew_id')->references('id')->on('crews');
$table->text('notes');
// ...
$table->timestamps();
});
Models:
namespace App\Models\Scheduling;
use Illuminate\Database\Eloquent\Model;
class Crew extends Model {
public $connection = "scheduling";
public $table = "crews";
public function events() {
return $this->hasMany('App\Models\Scheduling\Event', 'id', 'crew_id');
}
public static function active() {
return Crew::where('active', 1)->get();
}
}
namespace App\Models\Scheduling;
use Illuminate\Database\Eloquent\Model;
class Event extends Model {
public $connection = "scheduling";
public $table = "events";
public function crew() {
return $this->belongsTo('App\Models\Scheduling\Crew', 'crew_id', 'id');
}
}
If I run Crew::find(102)->events; I end up with an empty collection.
If I run Events::where('crew_id', 102)->get(); I end up with the list of events I expected.
Any idea what I'm doing wrong here?
Your definition of events relation is invalid - you pass the arguments in wrong order.
Replace:
return $this->hasMany('App\Models\Scheduling\Event', 'id', 'crew_id');
with
return $this->hasMany('App\Models\Scheduling\Event', 'crew_id', 'id');
or simply
return $this->hasMany('App\Models\Scheduling\Event');
as you are using the default values for the column names, so no need to pass them to the relation definition.
I'm working with the following models: Game, User and Player where Player extends User. In this case Game and Player have a relationship of N:N and User extends Confide. So code stands like:
app/models/Game.php
<?php
class Game extends Eloquent {
protected $guarded = array();
protected $table = 'users';
public $timestamps = false;
public function players(){
return $this->belongsToMany('Player');
}
}
app/models/User.php
<?php
use Zizaco\Confide\ConfideUser;
class User extends ConfideUser {
protected $table = 'users';
public $timestamps = false;
protected $hidden = array('password');
//Here go original Confide functions
}
app/models/Player.php
<?php
class Player extends User{
public function games(){
return $this->belongsToMany('Game');
}
}
I've populated the pivot table called game_player. As player extends user, pivot table is like this:
game_player
id
game_id
user_id
But if I run this super simple example I have an error:
$game = Game::find($gameId);
$player = $game->players(); //Error in this line
Error
Call to undefined method Illuminate\Database\Query\Builder::players()
I'm confused because I'm not having the error about pivot table was not found so I could think relationship is created fine.
On the other hand if I var_dump games var I obtain:
var_dump($game)
object(Game)[181]
protected 'table' => string 'games' (length=5)
//more var info about DB
protected 'relations' =>
array (size=0)
empty
protected 'hidden' =>
array (size=0)
empty
protected 'visible' =>
array (size=0)
empty
protected 'guarded' =>
If relationship would be created fine... shouldn't relations var have any data?
Thanks!
Just pointing out somethings that could solve the problem:
Your Game.php has the wrong table name.
When you get players, the line should be:
$game = Game::with('players')->find($gameId);
$player = $game->players;