I have two Eloquent models:
1) Post
class Post extends Model
{
protected $table = 'posts';
protected $fillable = ['id', 'user_id', 'product_id', 'site_id', 'link_id', 'body', 'created_at', 'updated_at'];
public function user(){
return $this->belongsTo(User::class);
}
public function product(){
return $this->belongsTo(Product::class);
}
2) Product
protected $table = 'products';
protected $fillable = ['id', 'user_id', 'manufacturer_id', 'shift_product_id', 'name', 'english_name',
'slug', 'text', 'spec', 'live', 'created_at', 'updated_at'];
public function posts(){
return $this->hasMany(Post::class);
}
I need to get the product from a post
I do that:
$posts = Post::get();
foreach($posts as $key){
dd($key->product);
}
Like this it returns NULL
If I do like this:
dd($key->product());
I get the product but I can't to use that
but I need to get something like that to use whant I need:
Try to point out foregin key and other key in relation, examples:
public function post()
{
return $this->belongsTo('App\Post', 'foreign_key', 'other_key');
}
public function user()
{
return $this->belongsTo('App\User', 'foreign_key', 'other_key');
}
More: https://laravel.com/docs/5.5/eloquent-relationships
i found my problem
i dont have in the DB product with ID = 1
:/
stuped problem
thanks for all the help i leran alot from u.
The relationship probably doesn't exist in the database.
Based on your fillable array on Post, the way you have the relationships setup looks correct as you are following naming conventions for keys and your belongsTo relationship methods have the correct name for convention.
$post->product() is not returning your Product model. It is returning a Relation type object (BelongsTo). This is used for querying the relationship. $post->product would be the dynamic property for the relationship that would return the already loaded relationship or load the relationship and give you the result.
Laravel 5.5 Docs - Eloquent - Relationships - Relationship Methods Vs. Dynamic Properties
If the relationships are setup correctly $post->product being null would mean the relationship doesn't actually exist in the database, no matching id in products for product_id or product_id being null. (assuming no foreign key constraint)
Side note: eager loading the relationship would be a good idea:
$posts = Post::with('product')->get();
I just came across this post because I got a similar error while working on a project.
What I discovered is that when you query a model with the all() method, it ignores the related softdeleted rows.
When you try to access them tho, you get the null
Remember to hit save() after associate and dissociate. Got me a couple of times:
$model->relation()->associate($record)->save();
Related
I am trying to get this problem fixed for hours now and I just don't get what I am doing wrong.
I want to get all entries of my tables where my id of posts equals the id of tables bewerbungens.
So I get all applications of every user existing with the corresponding title of the post the user applied to.
I asked a question here before and got resources to add relationships, which I did, as seen here:
Bewerbungen Model:
protected $fillable = [
'bewerber_email',
'Stellenanzeigen_ID',
'is_Accepted',
'accept_Date',
'is_Canceled',
'cancel_Date',
'is_Received',
'receive_Date',
'is_Canceled_Bewerber',
'cancel_Date_Bewerber',
'lebenslauf_File',
'zeugnis_File',
'anschreiben_File',
'weitere_Doks',
];
public function post() {
return $this->belongsTo('Post', 'Stellenanzeigen_ID', 'Bewerbung_ID');
}
and here in my Post model:
protected $fillable = [
'titel',
'startdate',
'enddate',
'beschreibung',
'standort',
'type_name',
'abteilung_name',
'kontakt',
'isActive',
'lebenslauf',
'zeugnisse',
'anschreiben',
'weitere_Doks',
'is_Permitted',
'job_start',
];
public function bewerbungen() {
return $this->belongsToMany(Bewerbungen::class);
}
Here is my Controller code where I try to get the entries:
$dummy = Post::with('Bewerbungen.post')->get();
But I get the error:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'portal.bewerbungen_post' doesn't exist (SQL: select bewerbungens.*, bewerbungen_post.post_id as pivot_post_id, bewerbungen_post.bewerbungen_id as pivot_bewerbungen_id from bewerbungens inner join bewerbungen_post on bewerbungens.id = bewerbungen_post.bewerbungen_id where bewerbungen_post.post_id in (1, 2, 3, 4))
I also tried this instead:
$dummy = Post::where('id', 'Stellenanzeigen_ID')->get();
But it just returns an empty set.
How can I fix this?
Edit: Post Model
protected $fillable = [
'titel',
'startdate',
'enddate',
'beschreibung',
'standort',
'type_name',
'abteilung_name',
'kontakt',
'isActive',
'lebenslauf',
'zeugnisse',
'anschreiben',
'weitere_Doks',
'is_Permitted',
'job_start',
];
public function location() {
return $this->hasOne(Standort::class);
}
public function job_type() {
return $this->hasOne(Jobtypes::class);
}
public function bewerbungen(): BelongsToMany
{
return $this->belongsToMany(Bewerbungen::class, 'bewerbungens');
}
I had the bewerbungen() method as suggested in the comment, I just played around with it so it looks different, but it is currently not in use since it didn't work
The SQL Error said that there's no bewerbungen_post table, since you use belongsToMany with only one argument. As mentioned here, if your relationship's intermediate table name is different with the Laravel Behavior, then add the relationship's intermediate table name to the second argument, or Laravel will join the two table for the relation table's name. For example:
public function bewerbungen() {
return $this->belongsToMany(Bewerbungen::class, 'bewerbungen_post');
}
I've checked your previous question, and I think that the Post model joined directly to the Bewerbungen model, so the relation in the Post Model should looks like this:
public function bewerbungens(): HasMany
{
// It's mean that `Post` has many `Bewerbungen` where `Stellenanzeigen_ID` = `posts.id`
return $this->hasMany(Bewerbungen::class, 'Stellenanzeigen_ID', 'id');
}
And in the Bewerbungen model:
public function post(): BelongsTo
{
// It's mean that `Bewerbungen` owned by Post as `Stellenanzeigen_ID` = `posts.id`
return $this->belongsTo(Post::class, 'Stellenanzeigen_ID', 'id');
}
If you want to get Post with all Bewerbungen owned by Posts:
// You will get All Post with all Bewerbungen each Post
$posts = Post::with('bewerbungens')->get();
Vice versa:
// You will All Bewerbungen and One Post for every Bewerbungen
$bewerbungen = Bewerbungen::with('post')->get();
All details about relationship could be found in Laravel Documentation.
I am struggling with an eloquent request. Let me explain what I want to do:
I have two models: User and Item
One User can have many Item and one Item belongs to One user.
I wrote the two method for this relation in my models as followed:
class Item extends Model
{
public function user() {
return $this->belongsTo(User::class);
}
}
class User extends Model {
public function items() {
return $this->hasMany(Item::class, 'items', 'user_id', 'user_people_id');
}
}
I try to access to the items from my controller its user's relation with:
public function index()
{
$items = Item::with('user')->get();
dd($items);
FYI: I seeded my items table with 10 items and my user table with 4 users:
items table:
users table:
My problem is that in the when I check my query with dd() here is what I get: Only the 4 first items get the relation, the others 6 return a null value
Relation working:
Relation returning null:
Thank you for helping me!
According to Laravel doc, hasMany relationship parameters are the following:
return $this->hasMany(Myclass::class, 'foreign_key', 'local_key');
So try to change your relationship in your User class like that
// change this
return $this->hasMany(Item::class, 'items', 'user_id', 'user_people_id');
// to this
return $this->hasMany(Item::class, 'user_people_id', 'id');
The easiest solution would be to rename your foreign key to user_id. That is what Laravel expects, so you won't need to deal with extra arguments in your hasMany() functions.
If you can't do that I think this'll work: return $this->hasMany(Item::class, 'user_people_id');.
Please try to add all in your query to see if it will work:
Update
public function index()
{
$items = Item::all();
dd($items);
}
In a "normal" relationship I can do something like this to select only a few columns while eager loading (using with):
->with(['reported' => function ($query) { $query->select(['nick','id']); } ])
But how to do it when working with polymorphic relationship where the columns i want to select are different according to the model morphed?
I have already tried using the query like a normaly do, also tried using a morph clause, but there is no select funciton on it.
--
Edited:
ReportMessages (model)
public function author(){
return $this->morphTo();
}
User (model)
protected $fillable = ['name', (...)];
public function reportMessages(){
return $this->morphOne('App\ReportMessage', 'author');
}
Jogador (model)
protected $fillable=['nick', (...)];
public function reportMessages(){
return $this->morphOne('App\ReportMessage', 'author');
}
And i want to select (when eager loading) only the nick ,when it is Jogador model that is morphed, and only the name, when User is the model morphed.
Try this
$query->with(['reported' => function($query){ $query->select(['id','nick']) } ])->orderBy('created_at', 'ASC');
Been learning laravel for 4 days and im trying to fix this error for 2 hours and i cant still fix it. I can save on one to many relationship but i cant retrieve data i think there something wrong with the relationship. Im trying to retrieve posts on user using this line but im getting not empty results on users but empty result on posts. Same thing happening on categories and posts which is many to many relationship but i cant save on many to many.
$users = User::with('posts')->get();
ANd im getting an error when i use this the error is
Undefined property: Illuminate\Database\Eloquent\Collection::posts()
$users = User::where('user_id','=','2')->get();
$posts = $users->posts()->get();
Heres my user Model
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $primarykey = 'user_id';
protected $table = 'users';
public function posts(){
return $this->hasMany("App\Post");
}
}
Heres my posts Model
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $primarykey = 'id';
protected $table = 'posts';
public function post_validation_rules(){
return [
'post_title' => 'required|min:5|unique:posts',
'post_body' => 'required'
];
}
public function user(){
return $this->belongsTo("App\User");
}
public function categories(){
return $this->belongsToMany('App\Category', 'category_id', 'category_id');
}
}
Categories Post
class Category extends Model
{
protected $primarykey = 'category_id';
protected $table = 'categories';
public function posts(){
return $this->belongsToMany('App\Post', 'post_id', 'id');
}
}
Database
Posts Table
id
user_id
post_title
post_body
createad_date
updated_date
Users Table
user_id
username
email
pass
createad_date
updated_date
You can only call relations on a single object, not on an entire collection. $users is a collection of User objects.
If you want a single user object, use the first() function to get the first User object that matches.
$user = User::where('user_id','=','2')->first();
$posts = $user->posts;
Update:
To get the posts directly in the user object, you need to use the with function:
$user = User::with('posts')->where('user_id','=','2')->first();
Try to declare the field that have the relation between your tables then, for example:
$this->hasMany(App\Post::class, 'user_id', 'user_id');
Laravel is searching for a field id in User table but it does not exist. so with this way you will tell it that the field you look is user_id
I've got Tag and Attendee Eloquent models, they are in many-to-many relation. Pivot table has also two more attributes – value_int and value_string. My Attendee model looks like this:
class Attendee extends Model
{
public $timestamps = false;
protected $fillable = [
'event_id'
];
public function tags() {
return $this->belongsToMany('App\Models\Tag', 'attendee_tag', 'attendee_id', 'tag_id')
->withPivot(['value_string', 'value_int']);
}
public function scoreTagValue($tag_id) {
return $this->tags->where('tag_id', '=', $tag_id)->first();
}
}
What I want is to obtain pivot values based on Attendee model and variable tag_id, so I've written scoreTagValue function, but it always returns null and I don't know why :( I'm calling it this way:
$attendee->scoreTagValue($tag_id). Thanks for your help :)
You need to access the relation, not the property:
public function scoreTagValue($tag_id) {
return $this->tags()->where('tag_id', '=', $tag_id)->first();
}
Also, according to the docs, withPivot() does not take an array, so:
->withPivot('value_string', 'value_int');