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.
Related
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();
I am currently learning Laravel and I have an issue which I can't seem to find a solution for. I have a many-to-many relation between two tables that always returns nothing. Let me show you the basic setup:
My posts Model:
// App\Post.php
protected $fillable = [
'name',
'description'
'videopath'
];
public function Tags()
{
return $this->belongsToMany('App\Tag');
}
public function Cats()
{
return $this->belongsToMany('App\Cat');
}
My tags model:
// App\Tag.php
protected $fillable = [
'name',
'description'
];
public function exercises()
{
return $this->belongsToMany('App\Exercise');
}
My posts controller:
// PostController.php
public function show($id)
{
$post = Post::find($id);
return view('posts', ['post'=>$post];
}
The view:
// posts.blade.php
#foreach($post->tags() as $tag)
//do stuff
#endforeach
The intermediate table is called post_tag and contains the post_id and tag_id columns. At first it returned the results as expected but after some while all of my posts didn't return any tags anymore. The cats model looks similar to the tags model. Anyone has an idea?
Check the name of your Tags function. In your view you are calling "tags" instead of "Tags".
Have you created the intermediate table in your database? If so, check the naming convention (alphabetic order) that Laravel uses to find it: in your case it should be tag_post. if not, customize the name of the table when defining the relationship.
Many To Many
Many-to-many relations are slightly more complicated than hasOne and hasMany relationships. An example of such a
relationship is a user with many roles, where the roles are also
shared by other users. For example, many users may have the role of
"Admin". To define this relationship, three database tables are
needed: users, roles, and role_user. The role_user table is derived from the alphabetical order of the related model names, and contains the user_id and role_id columns.
Taking your view:
#foreach($post->tags() as $tag)
//do stuff
#endforeach
$post->tags() will return the relationship instead of the actual collection. You want $post->tags instead or $post->tags()->get().
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');
I have a problem with displaying data from the form. He wants to load the data from two tables joined the foreign key.
I do not know what I'm doing wrong because I Chaly time returns the message:
Undefined property: Illuminate\Database\Eloquent\Relations\HasMany::$file
offers tabel:
id
user_id
title
...
photosofoffers tabel:
id
offer_id <- primary key offers.id
file (url photos)
...
my view:
#foreach($offers as $offer)
{{ HTML::image($offer->photosofoffers()->file, $offer->title, array('width'=>'50')) }}
my model Offer:
protected $fillable = array('id_category','user_id', 'title', 'description', 'price', 'availability');
public static $rules = array(
'id_category'=>'required|integer',
'title'=>'required|min:2',
'description'=>'required|min:2',
'price'=>'required|numeric',
'availability'=>'integer'
);
public function photosofoffers(){
return $this->hasMany('Photosofoffer');
}
public function category() {
return $this->belongsTo('Category');
}
}
my model Photosofoffer
<?php
class Photosofoffer extends Eloquent {
public function offer(){
return $this->belongsTo('Offer');
}
public function offers() {
return $this->hasMany('Offer');
}
}
How to display ads to load any pictures from another table?
hasMany means there are many photos of one offer. Therefore is it wise to call $something->photosofoffer()->photo ? If the return is an object, you'll definitely get an error.
First do dd($offer->photosofoffers()) or dd($offer->photosofoffers) to see what's happening. Then, if the object is properly being derived, You need to check loop through it. like #foreach($offer->photosofoffers as $photo) your loop of diplaying image #endforeach.
If there is nothing being derived, change the Controller function where you collect the actual $offer and make it Model::with('photoofoffers')->get() or first()
That should clear this up.
Hope this helps.
YK.