Eloquent not linking tables - php

So I've got 3 tables. But Laravel fails to link the tables to eachother, I feel like I'm missing a really small thing but I can't seem to find it.
Controller
$data = Item::all();
$clipper = $data->first();
dd($clipper->attributes());
Item
protected $table = 'item';
protected $primaryKey = 'item_id';
public $timestamps = false;
public function attributes() {
return $this->hasMany('App\Attributes', 'item_id');
}
Atrributes
protected $table = 'attributes';
protected $primaryKey = 'attr_id';
public $timestamps = false;
public function name() {
return $this->hasOne('App\Attributesname', 'name_id');
}
Attributes Name
protected $table = 'item_attributes';
protected $primaryKey = 'item_attr_id';
public $timestamps = false;
Result of dd
Database design

Laravel links relations fine, see you output parent model is the Item, related model is the Atribute, try this to see related data (not relation) :
$data = Item::all();
$clipper = $data->first();
dd($clipper->attributes);

Related

Create one to many table relationship with text input Laravel

I have two tables with a one to many relationship - gratitude_journal_entries and self_gratitudes. Multiple self gratitudes (which are submitted as text entries by the user) can apply to 1 gratitude_journal_entry. The data is passed to these two tables via a form.
I am trying to store the self gratitude text entries in an array and then pass these to the self_gratitude table along with the foreign key from the gratitude_journal_entries table.
The problem I'm having is I'm not sure how to take the input from the array and store this in the self_gratitude column.
Here are the columns for the gratitude_journal_entries table
Here are the columns for the self_gratitudes table
Here are the models and the store method in my controller
class SelfGratitudes extends Model
{
protected $table = 'self_gratitudes';
public $primarykey = 'id';
public function gratitudeJournalEntries() {
return $this->belongsTo(GratitudeJournalEntry::class);
}
}
class GratitudeJournalEntry extends Model
{
protected $table = 'gratitude_journal_entries';
public $primarykey = 'id';
public $timestamps = true;
public function user() {
return $this->belongsTo('App\User');
}
public function selfGratitudes()
{
return $this->hasMany(SelfGratitudes::class);
}
public function store(Request $request)
{
$this->validate($request, [
]);
$gj_entry = new GratitudeJournalEntry;
$gj_entry->user_id = auth()->user()->id;
$gj_entry['entry_date'] = date('Y-m-d H:i');
$self_gratitudes = $request->has('self_gratitudes') ? $request->get('self_gratitudes') : [];
$tj_entry->save();
$gj_entry->selfGratitudes()->sync($self_gratitudes);
return redirect('/dashboard')->with('success', 'You submitted a new journal entry');
}
If you want to keep array in database you can use casting on your columns:
laravel document
class SelfGratitudes extends Model
{
protected $casts = [
'self_graitude' => 'array',
];
protected $table = 'self_gratitudes';
public $primarykey = 'id';
public function gratitudeJournalEntries() {
return $this->belongsTo(GratitudeJournalEntry::class);
}
}

Laravel 4 deleting multiple models related by foreign keys

So I have three models and when when one of them dAgency is deleted delete-() I'd like all three to be deleted. The problem is that two of them are being deleted, while the top parent one DemDataSet isn't being deleted. Additionally, when I call:
echo "<pre>", dd(dAgency::find(21)->DemographicReport()->DemDataSet()->get()), "</pre>";
I get this error: Call to undefined method Illuminate\Database\Query\Builder::DemDataSet() But when I try:
echo "<pre>", dd(dAgency::find(21)->DemographicReport()->get()), "</pre>";
It works. So I know the problem is my relation between my DemDataSet model. Below is my model:
<?php
class DemDataSet extends Eloquent {
public $timestamps = false;
protected $connection = 'epcr_dem_data';
protected $table = 'DEMDataSet';
protected $primaryKey = 'pk_DEMDataSet';
public function DemographicReport(){
return $this->hasOne('DemographicReport','fk_DEMDataSet','pk_DEMDataSet');
}
}
class DemographicReport extends Eloquent {
public $timestamps = false;
protected $connection = 'epcr_dem_data';
protected $table = 'DemographicReport';
protected $primaryKey = 'pk_DemographicReport';
public function DemDataSet (){
return $this->belongsTo('DemDataSet','fk_DEMDataSet','pk_DEMDataSet');
}
public function dAgency(){
return $this->hasOne('dAgency','fk_DemographicReport','pk_DemographicReport');
}
public function delete(){
parent::delete();
return $this->DemDataSet()->delete();
}
}
class dAgency extends Eloquent {
public $timestamps = false;
protected $connection = 'epcr_dem_data';
protected $table = 'dAgency';
protected $primaryKey = 'pk_dAgency';
public function DemographicReport(){
return $this->belongsTo('DemographicReport','fk_DemographicReport','pk_DemographicReport');
}
public function dAgency_10(){
return $this->hasMany('dAgency_10','fk_dAgency','pk_dAgency');
}
public function delete(){
parent::delete();
return $this->DemographicReport->delete();
}
}
?>
I've been wrestling with this one for two days now! I really appreciate you taking the time to look at this.
The right way to query laravel model with relationship is this way:
//This is to pull all DemDataSet from DemographicReport
dAgency::find(21)->DemographicReport()->first()->DemDataSet;
//If you need further query, then you call DemDataSet as a method
dAgency::find(21)->DemographicReport()->first()->DemDataSet()->where('your condition here')->get();

Many-to-many (belongsToMany) Laravel relation doesn't seem to work under HHVM

MySQL tables:
posts
tags
post_tag (with columns post_id and tag_id)
// Post.php model
class Post extends Eloquent {
protected $table = 'posts';
public $timestamps = true;
protected $guarded = ['id'];
public function tags()
{
return $this->belongsToMany('Tag');
}
}
// Tag.php model
class Tag extends Eloquent {
protected $table = 'tags';
public $timestamps = false;
protected $guarded = ['id'];
public function posts()
{
return $this->belongsToMany('Post');
}
}
// on routes.php
Route::get('/', function()
{
$post = Post::find(44);
echo $post . '<br>';
$tag = Tag::find(28);
echo $tag;
return $post->tags;
});
when hitting / it prints post:44, it prints tag:28 and gives
ErrorException Cannot use a scalar value as an array
when accessing tags property that is on Post.php tags() function.
bare in mind that on post_tag's table there's an entry with post_id=44 and tag_id=28 but it could be empty.
Laravel/php gives me that error while trying to access the belongsToMany('Tag') method.
what am I doing wrong?
Should be fixed on February update: http://www.hhvm.com/blog/3287/hhvm-2-4-0
I believe you need to use eager loading:
$post = Post::with('tag')->find(28);
I don't have a laravel setup in front of me to test. So find might not be chainable, so you might need to do this:
$post = Post::with(array('tag' => function($query)
{
$query->where('id', '=', 44);
}))->get();

Accessing nested relationship with Laravel 4

I'm having trouble figuring out how to access a nested relationship within Laravel. The specific example I have is a Movie that has many entires in my Cast table which has one entry in my People table. These are my models:
MOVIE
class Movie extends Eloquent {
protected $primaryKey = 'movie_id';
protected $table = 'movie';
// Relationships
public function cast()
{
return $this->hasMany('MovieCast', 'movie_id');
}
}
MOVIECAST
class MovieCast extends Eloquent {
protected $table = 'movie_cast';
public function person()
{
return $this->hasOne('Person', 'person_id');
}
public function netflix()
{
return $this->belongsTo('Movie', 'movie_id');
}
}
PERSON
class Person extends Eloquent {
protected $primaryKey = 'person_id';
protected $table = 'people';
public function movieCast()
{
return $this->belongsTo('MovieCast', 'person_id');
}
}
In my controller I can access the cast (containing person_id and role_id) like so:
public function movie($id)
{
$movie = Movie::find($id);
$cast = $movie->cast();
return View::make('movie')->with(array(
'movie' => $movie,
'cast' => $cast
));
}
...but I don't know how to access the corresponding name field in my People table.
EDIT 1:
Using the classes exactly as defined below in #msturdy's answer, with the controller method above I try to render the person names like so inside my view:
#foreach($cast->person as $cast_member)
{{$cast_member->person->name}}
#endforeach
Doing this i get the error:
Undefined property: Illuminate\Database\Eloquent\Relations\HasMany::$person
I don't know if it makes a difference or not but I have no id field on my People table. person_id is the primary key.
It should be simple, once you have accessed the cast...
Route::get('movies', function()
{
$movie = Movie::find(1);
$cast = $movie->cast;
return View::make('movies')->with(array(
'movie' => $movie,
'cast' => $cast));
});
Note: at this point, $cast is an instance of the Collection class, not a single object of the MovieCast class, as the
relationship is defined with hasMany()
you can iterate over it in the View (in my case /app/views/movies.blade.php
#foreach($cast as $cast_member)
<p>{{ $cast_member->person->name }}</p>
#endforeach
Class definitions used for testing:
class Movie extends Eloquent {
protected $primaryKey = 'movie_id';
protected $table = 'movie';
public $timestamps = false;
// Relationships
public function cast()
{
return $this->hasMany('MovieCast', 'movie_id');
}
}
class MovieCast extends Eloquent {
protected $table = 'movie_cast';
public $timestamps = false;
public function person()
{
return $this->hasOne('Person', 'person_id');
}
}
class Person extends Eloquent {
protected $primaryKey = 'person_id';
protected $table = 'people';
public $timestamps = false;
public function movieCast()
{
return $this->belongsTo('MovieCast', 'person_id');
}
}

Eloquent ORM Movie Location

I am using Laravel 4 and eloquent orm to build a movie session database.
Now I have the following Models.
class Location extends \Eloquent
{
public $timestamps = false;
public $table = 'movsys_location';
protected $fillable = array('name', 'desc');
public function sessions(){
return $this->hasMany('Session', 'location_id');
}
}
class Session extends \Eloquent
{
public $timestamps = false;
public $table = 'movsys_session';
protected $fillable = array('time');
public function location(){
return $this->hasOne('Location', 'id');
}
}
(Note: These models are stripped to the necessary code.)
Now in my controller, I have the following.
$Sessions = Session::all();
foreach($Sessions as $Session){
echo (isset($Session->location->name) ? $Session->location->name : 'NO LOCATION');
}
And this is what my database looks like:
Now, everything seems to work, but even though both sessions have the same location, ONLY the first session will return the name of the location! The second echo will return "NO LOCATION".
Any idea or help as to why would be appreciated. If this answer isnt clear enough let me know.
Try this one in place of yours:
class Session extends \Eloquent
{
public $timestamps = false;
public $table = 'movsys_session';
protected $fillable = array('time');
public function location(){
return $this->belongsTo('Location');
}
}

Categories