6

I have subject table that contains

id  name 

and languages table that contains

id subject_id

and division table

id name 

finally subject-division table (pivot table)

id subject_id  division_id

now exist one-To-one relationship between subject table and languages table and many-To-many relationship between subject table and division table, i need to pluck only the subjects of subject table without the languages by using the relationship function

now i can get the languages only of the subject table of the relationship function In Division Model as the following

    public function langSubject ()
{
    return $this->belongsToMany('Subject' , 'subject_division','division_id','subject_id')
                ->join('lang_subject', 'lang_subject.subject_id' ,'=', 'subject.id')->get();

}

But till now I can't get the subjects only without the languages

Any Suggestions ?

Muhammad Atallah
  • 976
  • 2
  • 12
  • 34
  • 1
    Your question is pretty unclear. You need to be more specific as to which model you're trying to access subjects (with no related language) through. If I'm reading your question correctly: you're trying to find subjects for which there is no relationship defined. This is not something that the relationship function should be used for, as you're literally trying to solve the opposite problem for which it was designed. – Jim Rubenstein Apr 28 '15 at 13:19
  • 1
    firstly , thanks sir Jim for comment,look i have one table that carries all subjects like(English,Math,German,Science ....) Subjects BelongsToMany Divisions in subject_division (my pivot table) and also exist table is called lang_table this table has one-To-one relationship with subjects table that's mean that this table will be carry languages only like(English,German) Now i need pluck (Math,Science) only from subject table without (English,German) . – Muhammad Atallah Apr 28 '15 at 14:28
  • Maybe you can use a whereIn and whereNotIn with a subquery (http://stackoverflow.com/questions/16815551/how-to-do-this-in-laravel-subquery-where-in). So a query like SELECT * FROM division inner join subject on ... where subject.id not in (SELECT subject_id from languages) – Rickkwa Apr 28 '15 at 20:33

2 Answers2

0

You need to add the clause ->select('tableName1.fieldName1','tableName2.fieldName2','tableName3.fieldName3') to your statement after the join statement to get the tableName.fieldName and you may need to use leftJoin instead of join to get the results whether if there is a match or not.

0

Check out Eloquent relationship documentation -> sub headline "Querying Relationship Existence". There it mentions ::has method, which you could use in fashion

Division::has('subject.lang', '<', 1)->get()

Or at least that's the theory. Haven't had the need for it yet ;-)

It should be supported by Laravel 4 as well.

trm42
  • 2,536
  • 2
  • 19
  • 16